Skip to content
Advertisement

How can I get the value of an input which is a previous sibling?

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 class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input class="ImageUrl"> <span class="Btn">Go</span>
    </div>
  </div>
</div>

<div class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input class="ImageUrl"> <span class="Btn">Go</span>
    </div>
  </div>
</div>

Advertisement

Answer

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 class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input value="https://via.placeholder.com/400"> <button>Go</button>
    </div>
  </div>
</div>

<div class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input value="https://via.placeholder.com/400"> <button>Go</button>
    </div>
  </div>
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement