Home > front end >  How can I get the value of an input which is a previous sibling?
How can I get the value of an input which is a previous sibling?

Time:09-13

I'm trying to switch a background image with a URL from a input field. With one block it works, for a second it only works if I use the first one first, or else it gets a undefined value. How do I grab the ImageUrl value for each block only?

jQuery($ => {
  $(".Btn").click(function() {
    jQuery(this).closest('.parent').find('.child')
        .css("backgroundImage", "url('"   jQuery(".ImageUrl").val()   "')");
  });
});
.child {
  width: 300px;
  height: 300px;
  background: #ccc;
  background-size: cover;
}

.wrapper {
  width: 300px;
  float: left;
  margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
    </div>
    <div >
      <input > <span >Go</span>
    </div>
  </div>
</div>

<div >
  <div >
    <div >
    </div>
    <div >
      <input > <span >Go</span>
    </div>
  </div>
</div>

CodePudding user response:

There are lots of ways to traverse the DOM to accomplish this. Here's one.

Note that I've made your button an actual button. This is important for accessibility (and good semantics in general). Style accordingly. You could also apply aria-role="button" to a span if you prefer.

jQuery($ => {
  $(".switch button").click(function() {
    const imgUrl = $(this).prev('input').val();

    $(this).closest('.parent').find('.child')
      .css("backgroundImage", "url('"   imgUrl   "')");
  });
});
.child {
  width: 300px;
  height: 300px;
  background: #ccc;
  background-size: cover;
}

.wrapper {
  width: 300px;
  float: left;
  margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
    </div>
    <div >
      <input value="https://via.placeholder.com/400"> <button>Go</button>
    </div>
  </div>
</div>

<div >
  <div >
    <div >
    </div>
    <div >
      <input value="https://via.placeholder.com/400"> <button>Go</button>
    </div>
  </div>
</div>

  • Related