简体   繁体   中英

How to check if textbox is entered to allow user to select radio button javascript

I want to make sure user inputs text in the text field before being able to select the radio button. If the gateway field is blank, do alert the user that they haven't inputted anything in the field and return.

This is what I have so far:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="gatewayInput"> <form> <input type="text" name="gateway" placeholder="Gateway Name"><br><br> </form> </div> <div class="box1"> <form method="post" action="javascript:alert('Success')" onsubmit="validate()"> <label class="col">Air/Ground</label> <span class="col"> <input type="radio" name="option" id="r1" value="1" /> <label for="r1">Air</label> <input type="radio" name="option" id="r2" value="2" /> <label for="r2">Ground</label> </span> <span class="col"> <input type="submit" class="button"/> </span> </form> </div> <script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script> <script type="text/javascript"> function validate() { if ((document.getElementsByName("gateway")[0].value == '')) { alert('Response required'); return false; } else { alert('Sucess'); return true; } } console.log("this is my value:" + document.getElementsByName("gateway")[0].value); $(".button").click(function(event){ if ( validate() == true ) { event.preventDefault(); $.ajax({ url:"testexec.php", type: "POST", data: {option: $('input[type=radio]:checked').val()}, dataType: "text", success:function(result){ $('#div1').html(result) } }); } }); </script> <div id="div1"></div> </body> 

I dont think this part is working, it doesnt seem to be calling my validate function:

<form method="post" action="javascript:alert('Success')"  onsubmit="validate()">

Also i am checking onsubmit, is there a way to alert the user before this? Like right when they click the radio button, alert them with the message?

And validate(e) { to the function declaration and e.preventDefault(); to the beginning of the function to prevent the form from submitting before running your code.

function validate(e) {
    e.preventDefault();
    if ((document.getElementsByName("gateway")[0].value == '')) {
        alert('Response required');
        return false;
    } else {
        alert('Sucess');
        return true;
    }
}

onsubmit="validate()" is duplicated with $(".button").click(function(event) . You can merge them together:

$(".button").click(function(event){
  validate();
  event.preventDefault();
  ...

Since you have event.preventDefault() , no need action or onsubmit on form.

<form method="post">

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