Dinesh Dinesh - 5 months ago 26
jQuery Question

getting attr id undefined on click button jquery

<select class="form-control newclass addvalue input_color" name="CandInv-54" id="sugar_id">
<option value="">Select Value</option>
<option selected value="ABSENT">ABSENT</option>
<option value="1">ADD</option>
</select>

<div id="sssugar_id">
<input id="myInput2" class="form-control" required="" placeholder="Fill Value Or Select Dropdown" style="margin-top: 5px;border-color: green;border-width: medium;" type="text">
<button type="button" id="mybtn2" class="btn btn-success button_class" style="margin-top: 5px;" onclick="addtest()">ADD</button>
</div>

<script>
function addtest(){
var xyz = $('#mybtn2').prev('select').attr('id');
alert('id ' + xyz);
}
</script>

Answer

Add parent('div') for getting selectbox.

function addtest(){
        var xyz = $('#mybtn2').parent('div').prev('select').attr('id');
        alert('id: ' + xyz);
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select class="form-control newclass addvalue input_color" name="CandInv-54" id="sugar_id">
    <option value="">Select Value</option>
    <option selected value="ABSENT">ABSENT</option>
    <option value="1">ADD</option>
</select>

<div id="sssugar_id"> 
    <input id="myInput2" class="form-control" required="" placeholder="Fill  Value Or Select Dropdown" style="margin-top: 5px;border-color: green;border-width: medium;" type="text">
    <button type="button" id="mybtn2" class="btn btn-success button_class" style="margin-top: 5px;" onclick="addtest()">ADD</button>
</div>

Comments