Combine checkbox values into string before submitting form

前端 未结 2 1280
予麋鹿
予麋鹿 2021-01-13 15:14

I am sending a form to an external server I have limited access to. I have a form with many check-boxes for different products the user is interested in. I need to send the

相关标签:
2条回答
  • 2021-01-13 15:46

    First you need to grab the name value pairs and store them to an object as such:

    var obj = {}; // this will hold your name value pairs
    

    From there you can use JSON to send the data to the server. JSON data is in string form when it is sent to the server.

    var json_string = JSON.stringify(obj);
    
    0 讨论(0)
  • 2021-01-13 15:54

    I'm just going to give you a hint on how to catch up the checked checkboxes once the form is submitted (DEMO).

    Imagine you have the following html:

    <form id="testForm">
        <input class="checkbox" name="one" type="checkbox">
        <input class="checkbox" name="two" type="checkbox">
        <input class="checkbox" name="three" type="checkbox">
        <input type="hidden" name="checkboxStr" id="checkbox_str">
        <button>Send</button>
    </form>
    

    You can add an event listener to form submission:

    var form = document.getElementById('testForm');
    
    try {
        form.addEventListener("submit", submitFn, false);
    } catch(e) {
        form.attachEvent("onsubmit", submitFn); //IE8
    }
    

    And then you can get all the needed checkboxes with for example its class name. Loop trough them and add the checked ones to an array which you later on join to a string.

    function submitFn(event) {
        event.preventDefault();
        var boxes = document.getElementsByClassName('checkbox');
        var checked = [];
        for(var i=0; boxes[i]; ++i){
          if(boxes[i].checked){
            checked.push(boxes[i].name);
          }
        }
    
        var checkedStr = checked.join();
    
        document.getElementById('checkbox_str').value = checkedStr;
        form.submit();
    
        return false;
    }
    

    You can now send this string via ajax or you can add a hidden form field and set the string as its value and submit the form without ajax.

    0 讨论(0)
提交回复
热议问题