简体   繁体   中英

How to do validation with JavaScript when the form is submitted?

I trying to get my drop down box work properly in JQuery dialog box. I have drop down with 4 different options. If I select just 2 out of 4 that have value A or B in that case my second drop down should allow me to select YES or NO else NONE. Here is my code for my drop down boxes:

 <div id="Dialog">
        <table>
            <tr><td align="left">Slecet Type</td>
            <td><select name="Type" id="Type">
                    <option value="A">One</option>
                    <option value="B">Two</option>
                    <option value="C">Three</option>
                    <option value="D">Four</option>
                </select>
           </td>
        </tr>
        <tr>
        <td align="left">Slecet Option</td>
        <td>
            <select name="drop" id="drop">
                <option value="">Select One</option>
                <option value="1">Yes</option>
                <option value="0">No</option>
                <option value="99">None</option>
            </select>
        </td>
    </tr>
    </table>
</div>

So if I select ONE or TWO in my first drop down, only in that case I can select YES or NO in my second drop down, else should be NONE. I tried to fix this with coldfusion validation but that did not work for me.

<cfif getQuery.Type EQ 'A' OR getQuery.Type EQ 'B'>
      <option value="1">Yes</option>
      <option value="0">No</option>
<cfelse>
      <option value="99">None</option>
</cfif>

So now I'm trying to solve this using jQuery but I can not get it to work. Here is my jQuery code where I tried to implement validation:

$("#Dialog").dialog({
            title:'Hello World',
            modal:true,autoOpen:false,width:600,
            buttons: { 
  'Continue': function(){mydrop = $('#drop');
            if($(mydrop).val() != 'A' || $(mydrop).val() != 'B'){alert('Please   select different');};$(this).dialog('close');} }
        }); 

I'm not sure if I can use this code inside of this function for Continue button or this should be placed somewhere else. If you know what I should change please let me know.

You would need to get the selected option value in order to validate instead of just checking the dropdown value.

if($('#drop option:selected').val() != 'A' || $('#drop option:selected').val() != 'B')

As per your suggestion on whether the validation logic should be placed inside the Continue button, if your validation only checks for value = 'A' or 'B' , then you can leave it where it is, but if the logic gets complex and requires more if-else checks, create another js function.

Here's a fiddle in action : http://jsfiddle.net/dmfawp8g/11/

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