Multipile forms with input and submit button with

2019-08-19 07:55发布

问题:

I have a Form with Input and a submit button (Javascript), I duplicated the form 3 times in order to create 3 different options, although these options use the same Javascript for input errors and for submission, this resulted in giving me an error if i do not enter value on the first form on the page, while I am trying to use the second or third form.

the JS file:

jQuery(function($){
$('form#unlock').on('submit', function (e){
    if($('#the_imei').val().length == 15){
        if($('#the_imei').val().indexOf('9900') === 0){
         alert('לפי המספר IMEI, ברשותכם מכשיר CDMA, אנא ראו מידע נוסף בעמוד פתיחת מכשירי CDMA');
         window.location = 'http://www.unlocker.co.il/sim-unlock-cdma-mobile-device';
         e.preventDefault();
             }
        return;
    }

    alert('אנא מלאו מספר IMEI בעל 15 ספרות');
    e.preventDefault();
}); 
})

And the page URL is: http://www.unlocker.co.il/shop/sim-unlock-htc-mobile-device/

thanks for any help

回答1:

The first thing that came to mind is if you are simply duplicating the form by copy and pasting the form code, is that you are duplicating any id's. ID's need to be unique. If you have more than one id with the same name, then Javascript will only recognize the first one in the page.

Edit:

To be more specific for your first form... (notice the input change of id to class)

<form id="unlock1" class="cart" enctype="multipart/form-data" method="post" name="unlock">
        <input class="the_imei" style="width: 80%; border-radius: 15px;" name="the_imei" type="text" value="" placeholder="מספר סידורי IMEI של המכשיר (חייג #06#*)"><br>
        <input class="add-to-cart" name="add-to-cart" type="hidden" value="39"><br>
        <button class="unlockButton" type="submit" value="submit">פתח לכל הרשתות בישראל </button>
</form>

Then for your script...

    jQuery(function($){
    $('form#unlock1').on('submit', function (e){
        if($('form#unlock1 > input.the_imei').val().length == 15){
            if($(this).val().indexOf('9900') === 0){
             alert('לפי המספר IMEI, ברשותכם מכשיר CDMA, אנא ראו מידע נוסף בעמוד פתיחת מכשירי CDMA');
             window.location = 'http://www.unlocker.co.il/sim-unlock-cdma-mobile-device';
             e.preventDefault();
                 }
            return;
        }

    alert('אנא מלאו מספר IMEI בעל 15 ספרות');
    e.preventDefault();
    }); 
   })