JQuery get the option of a checkbox checked - javascript

I'm doing some code where i need to get the option(value) from an checkbox checked
Here is how i create the checkbox
function createCheckbox(txt) {
var comb = document.createElement("Select");
comb.className = "something";
for (var i = 0; i < txt.length; i++) {
var option = document.createElement("OPTION");
var optionText = document.createTextNode(txt[i]); //some options
option.appendChild(optionText);
comb.appendChild(option);
}
return comb;
}
Function where i need to show the option that is selected
function foo{
var inputTextValue = document.getElementsByClassName("something");
var checkedValue = $(inputTextValue).is(':checked');
alert(checkedValue); //true/false
}
the alert only show true /false depeding if the checkbox is checked or not.But what i need its the option checked. I already tried $(inputTextValue).is(':checked').val().

Checkbox and Select are two different HTML Elements
For Getting the value of Selected option use
$(".something option:selected").val();

I think tou mix here between checkbox and select.
Select option is selected with :selected attribute.
Checkbox is checked with :checked attribute.

The value of a <select> is the value of the selected option.
$(".something").val()

Related

how to get all selected option select2

I have many select2 in one page so I want to get all selected option as a array
how it's possible?
i've tried this
console.log($("select").val());
but it just gives me the first selected option
I hope this will work :
var select = $("select");
var valArray = [];
select.each(function(index){
valArray.push($( this ).val());
});
console.log(valArray);

Create options onClick attribute

This is the idea: When I click on "word1" (or "word2") the select tag shows me the options. Once I click on one of the options, my script change "word1" (or "word2") whit the option. I can update the options, but once I click on one of them the script always write the last option.
The script write the same onClick attribute for all the options...
I've been searching a lot but I cannot understand why it happen, and how to solve it.
Here is the code:
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
option.onclick = function() {
currentElement.innerHTML = newWord;
};
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
Thanks in advance
You can not bind 'click events' on 'options' property of a 'select box'. You will need to bind a onchange event listner on the 'select element'. Inside the callback function of the change event listner put your code logic for updating word text. As the 'change' event listner is not in the scope of 'updatemyselect' function, you can store the last clicked element in a variable and use the same in the callback function for updating the desired word text. Please refer to the below code which I have edited.
var clickedElement;
function updatemyselect(currentElement, optionsList) {
clickedElement = currentElement;
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
/*option.onclick = function() {
currentElement.innerHTML = newWord;
};*/
mySelect.add(option);
}
}
document.getElementById("mySelect").addEventListener("change", updatePTag);
function updatePTag(){
clickedElement.innerHTML = this.value;
};
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
The reason why you are always getting the last option value is because you are using the newWord variable in your onclick function instead of an actual value, or reference to the currently selected option.
As a result, after you have finished going through the loop, the value of newWord is always equal to the last option text, so, regardless of which option is selected, when you are returning newWord, you will get the same value (i.e., either, "Fish" or "Whale").
Instead, try using currentElement.innerHTML = mySelect.value; in the onclick function.
First you need to set the value attribute on each option.
After you can use the onChange event on Select to display your value.
You can use Jquery to do this, its more easy
jquery select change event get selected option
Thanks to everybody.
I didn't realize that currentElement.innerHTML = newWord; was actually giving the value of the same variable to every onClick attribute.
I finally solved in this way, even if I think the solution of Arun Singh is better.
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
mySelect.onchange= function() {currentElement.innerHTML=mySelect.value;};
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i];
option.text = newWord;
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" value="a">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" value="b">Word2</p>

Dynamically creation select box options issue in IE8

I am using the following function to create a add options to my select box
//add options to the requested select box
addOptionsToSelect : function(__enum , obj, selected_value) {
$(__enum).each(function(i){
var optn = new Option(this.text, this.val)
if(selected_value === this.val){ optn.setAttribute('selected', 'selected') }
$(obj)[0].options.add(optn);
});
return obj
}
__enum is the key value pair containing the value and the text that we pass to the select option
obj is the select box obj which is also created dynamically
selected_value is the value that needs to set as selected on the select box.
The problem here is optn.setAttribute('selected', 'selected') works fine in all the browsers expect IE8.
I am looking for a workaround that will allow me to set the selected value in all the browsers dynamically.
I'd add an option to a like so:
var select = document.getElementById("drop-down");
var newOption = document.createElement("option");
newOption.innerHTML = 'hello';
select.appendChild(newOption);
Here's an example: my fiddle

How do I add items to multiple drop down lists at the same time with Javascript in Razor?

I'm creating an MVC form, and I have multiple checkboxes and two drop down lists. I have figured out how to populate the first DDL based on what boxes are checked (i.e. empty at the beginning, checking boxes fills the items). However, I want to add another DDL that has the same items and populates in the same manner. My code looks like this:
<script type="text/javascript">
function checkedToggle(value, checked) {
x = document.getElementById("filter1");
y = document.getElementById("filter2");
if (checked == true) {
var option = document.createElement("option");
option.text = value;
x.add(option, null);
y.add(option, null);
}
else {
for (i = 0; i < x.length; i++) {
if (x.options[i].value == value) {
x.remove(i);
y.remove(i);
}
}
}
}
</script>
The else statement obviously removes an item from the list once you uncheck the box.
Now, when you click a check box, rather than adding the item to both lists, it only adds to the second one, and I'm not exactly sure why. Any advice?
You need to create two elements, since in your code you just move the first DOM element to the second select.
var option = document.createElement("option");
var option2 = document.createElement("option");
option.text = value;
option2.text = value;
x.add(option, null);
y.add(option2, null);

Accessing HTML Form elements through Javascript

Can any guru show me how to get values from HTML Form element - RADIO BUTTON and CHECK BOX?
For example in case of text box we can get the value directly by getElementById(id).value;
But how to get the value for a combo box (drop down menu), radio button and checkbox ?
Thanks.
Drop down (<select>):
var el = document.getElementById('yourSelectId');
var value = el.options[el.selectedIndex].value;
If you're treating your select list as a multi-select (combobox) list, you have to loop through the options and check if they are selected:
var el = document.getElementByid('yourSelectId');
var selectedValues = [];
for (var i = 0; i < el.options.length; i++) {
if (el.options[i].selected) {
selectedValues.push(el.options[i].value);
}
}
// all selected values are now in the selectedValues array.
Radio buttons and checkboxes should also have value properties, but more appropriately I think I would only test whether they are checked:
var isChecked = document.getElementById('yourRadioOrCheckboxId').checked;
For checkbox, the element has a .checked property:
document.getElementById('foo').checked; // true or false

Categories

Resources