简体   繁体   中英

validate field in javascript and jquery

I have four radio buttons. If I select the last radio button then one textbox is appearing. I handled this scenario by jquery. Now I want to validate in such a way that if user gets this textbox means if user checked the last radio button, then he should provide some text.But in my case, if I check any one of the radio button, its telling to provide some text. The code is like:

    <input type="radio" name="bus_plan" id="smallBtn" value="1" />1
     <input type="radio" name="bus_plan" id="smallBtn" value="2" />2
     <input type="radio" name="bus_plan" id="smallBtn" value="3" />3
     <input type="radio" name="bus_plan" id="smallBtn" value="Promotional" />
      <span class="plantxt"><a style="cursor:pointer;" onclick="popup('popUpDiv')">Promotional Plan</a> (Please enter a promotional code)</span>
    <div class="reg-line" id="pr_code_id" style="display:none">
       <div class="reg-linea" align="left">Promotional Code: <sup>*</sup></div>
       <input type="text" name="bus_prcode" id="bus_prcode" class="reg-line-input" value="Promotional Code" onblur="if(this.value=='') this.value='Promotional Code'" onClick="if(this.value==this.defaultValue) this.value='';" />
       <br />
       <div>
            <div id="promotionalbox" style="display:none;font-size:13px;clear:both"></div>    
       </div>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){     
    $("input:radio[name=bus_plan]").click(function(){  
        var values = $(this).val();
        if(values == 'Promotional'){
            $('#pr_code_id').show();
        }else{
            $('#pr_code_id').hide();    
        }
    }); 
}); 
</script>

and in js if I alert the value of document.getElementById('bus_prcode').value then always it is showing Promotional code, which is only for last radio button value.

Your code is a bit of a mess which is the root of this problem. Remember, one element per ID.

You may also find it helpful to look at jQuery .is(), for example:

$('input[value="Promotional"]').is(':checked')

nb I do not suggest the above, you should use identifiers in the appropriate way first.

Also worth noting that your code works fine for me using Chrome. See an example (which I have expanded for you) here: http://jsbin.com/ofujal/3/

You should not have an element with the same ID (your radio buttons). Also, you're getting the textbox by running document.getElementById('bus_prcode') and not the radio button. You should give a unique ID to your last radio button, eg btnPromotional, then bind click to it:

$("#btnPromotional").click(...)

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