简体   繁体   中英

How to change the value of a previous check box that has been selected in JQuery?

Here is what I'm trying to do.

I have the ability to create a form when there is an option to create one in Javascript.

Here is an option to add an address:

    <a href="javascript:" onclick="addNewAddress();" id="newAddressUrl"><i class="fas fa-plus-circle"></i>  <span class="newUrlText">add new address</a>

Here is the form in question:

  <input type="text" class="form-control" id="new-address-1-%ID%" name="new-address-1-%ID%" placeholder="Address Line 1">

  <input type="text" class="form-control" id="new-address-2-%ID%" name="new-address-2-%ID%" 
placeholder="Address Line 2">

 <label for="message" class="control-label"><span class="billable-text"><?php _e('Primary Address'); ?></span></label>
                <label class="switch" for="primary-%ID%" style="margin-left: 10px;top: 10px;">
                    <input type="checkbox"  class="primary-%ID%" name="primary-%ID%" id="primary-%ID%" />
                    <div class="slider round gray"></div>
                </label>

Here is the javascript that generates the form:

  <script language="javascript">
    var newAddressIndex = 1;
    var addressarray = [];

    function addNewAddress() {
       var container = getElement("addressContainer");  

        addressarray.push(newAddressIndex);
    
         var htmlAddress = '<?php echo addslashes(App_String::stripBreaksTabsMultipleWhitespace($newAddress)); ?>';
        htmlAddress =  htmlAddress.replace(/%ID%/g, newAddressIndex);

        var node = document.createElement("div");
        node.innerHTML = htmlAddress;

        container.appendChild(node);
        $('#newAddressCount_'+newAssetIndex).val(newAssetIndex);    
        
        ++newAddressIndex;

        test(addressarray);
    }

What I'm trying to do is the following:

If the user selects the checkbox and then decides to select the next checkbox, I would like to change the previous checkbox from selected to no selected.

How would I go about doing that?

Thank you

I found a solution:

What I did was, that I created a function to get the current value of the checkboxes like this:

    getAddrValue(addressarray);

Then within the function the follwoing:

   function getAddrValue (addressarray) {
      $('#primary-'+index).change(function() {
          var checked = this.checked ? 1 : 0;

          prevCheckbox = index-1;

         if (checked == 1) {
                if (document.getElementById('primary-'+prevCheckbox) !== null ) {
                        let inputs = document.getElementById('primary-'+prevCheckbox);
                        inputs.checked = false;
                    }
         }                      
      });
   }
     

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