0

I have a page layout like the below and I need to set values in <select> as I have a form.

enter image description here

<form action="add.jsp">
    <input name="title" id="title"/>
    <input name="company" id="company" />           
    <select name="options" id="options">

    </select>           
    <button>Submit</button>

</form>

I want to add values to above <select/> from the checkboxes out side of the form which are

<input id="input-checkbox-1" name="input-checkbox" type="checkbox">Option 1
<input id="input-checkbox-2" name="input-checkbox" type="checkbox">Option 2
<input id="input-checkbox-3" name="input-checkbox" type="checkbox">Option 3

now don't have any idea of how to get values from checkboxes and add options to select using jQuery.

0

1 Answer 1

1

now don't have any idea of how to get values from checkboxes and add options to select using jQuery.

First, to get an HTML element, you can use $("css selector"), document.getElementById("id value"), or document.querySelector("css selector").

Here's a CSS selector syntax reference: http://www.w3.org/TR/selectors/#selectors

Next, to retrieve the value of a checkbox, you can refer to the .checked property of the element. It will be true if the box is checked and false otherwise.

document.querySelector("input").addEventListener("change",function(){
  alert(this.checked);
});
<input type="checkbox" />Check me

Finally, to add a value to a select element, create an option element, set its text and value, and add it to the select.

var select = document.querySelector("select");
var checkboxes = document.querySelectorAll('[type="checkbox"]');
for(var i = 0, len = checkboxes.length; i < len; i++){
  checkboxes[i].addEventListener("change",addOrRemoveMe);
}
function addOrRemoveMe(){
  if(this.checked){
    var option = document.createElement("option");
    option.value = this.name;
    option.text = this.name;
    select.appendChild(option);
  }else{
    select.removeChild(select.querySelector('[value="'+this.name+'"]'));
  }
}
<input type="checkbox" name="One"/> One<br/>
<input type="checkbox" name="Two"/> Two<br/>
<input type="checkbox" name="Three"/> Three<br/>
<select></select>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for great help, but when I submit the form I con't get values from the select box, I guess those values are not selected as I'm setting it as a hidden field, how can I make those options selected.
Add One line option.selected = 'selected'; after option.text = this.name;, I hope this solves issue.
@ArshadAli as you said it Solved my issue, thanks to Thriggle, he saved my life.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.