简体   繁体   中英

select input element before previous element in jquery

I had the below html code

{% for state in us_states %}
    <input id="{{state.0}}" type="checkbox" name="{{state.0}}" class="value_check"/>
    <span style="padding-left:20px;padding-right:20px;">{{state.1}}</span>
    <input id="id_{{state.1}}" type="text" name="{{state.0}}" class="input-block-level-b iph_lvl_b span2 must_be_float" placeholder="0.0">
{% endfor %}

So what i am trying is, when the user selects some value in the text input field above, and if the checkbox is not checked, then i should make an alert to him that "Please select the checkbox" . so i want to write a jquery onfocusout function , and want to find whether the checkbox is checked or not

Note

I want to find the in the way of finding the previous elements and their values, becasue as u can see in my code that i am generating them dynamically from for loop, so usually want to find the previous previous checkbox element and check whther its checked or not, if not then display an alert

$(document).ready(function(){
      $('.value_check').focusout(function() {
            console.log(this.id); 
            var prev = $('.value_check').prev()
            console.log(prev.attr(id)); 
      });        
   });

The focus out function is called a blur , and you should be using the blur on the actual text field, not the checkbox, so something like:

$("input[id^=id_]").blur(function() {
    var checked = $(this).siblings(".value_check").prop("checked");
    if (!checked)
        alert("Didnt check zeh box!");
});

$(".value_check").change(function() {
    if (!this.checked) 
        alert("You must check the box to continue");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM