Skip to content Skip to sidebar Skip to footer

Click Button To Get Value From Nearby Input?

I have a button that comes after an input in the HTML, and I want to use that button to retrieve the value from that input and perform an action. The problem I'm facing is that my

Solution 1:

Travel up the DOM with closest:

var inputValue = $('.an-button').closest('div').find('input').val();

Fiddle

Solution 2:

Try removing .find('input') , as .prev(".an-input") should return input element . Also note, <input /> tag is self-closing

$(".an-button").click(function() {
    var inputValue = $(this).prev(".an-input").val();
    console.log(inputValue)
    //window.open('http://a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber='+inputValue+'&passdocnumber=&go10=+GO+&requestid=0');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div><inputclass="an-input"type="text" /><buttonclass="ui-state-default inputButton an-button">GO</button></div>

Solution 3:

To target a sibling, it must be of similar type.

Try this instead:

$('.an-button').click(function() {
    var inputValue = $('.an-button').parent().find('.an-input').val();
    window.open('http://a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber='+inputValue+'&passdocnumber=&go10=+GO+&requestid=0');
});

Solution 4:

$('button.an-button').click(function() {
    var inputValue = $('.an-input:text').val();
  ... rest of code
})

Solution 5:

The input element has not end tag

more information here

the correct is <input />

Post a Comment for "Click Button To Get Value From Nearby Input?"