Understanding the each jquery function - Unexpected output - javascript

I am trying to wrap my head around the each function. In this fiddle here
I would like to iterate through the selected elements of the list box one by one.
Essentially I was expecting an output like this
found itemA
found itemB
However I get an output like this
found itemA,itemB
I would like to know why that is happening and how I can fix it.
This is the code I am using
HTML
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
JQuery
$( "#bid" ).click(function() {
$("#test").each(function () {
console.log("found " + $(this).val());
});
});

You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().
$( "#bid" ).click(function() {
$("#test > option").each(function () {
console.log("found " + $(this).text());
});
});

You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.
$("#bid").click(function() {
$("#test option").each(function() {
console.log("found " + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>

You'll want to use
$.each($("#test").prop("options"), function () {
console.log("found " + this.value);
});
or
$("#test").children().each(function () {
console.log("found " + this.value);
});

Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/
HTML
<select multiple="multiple" size="5" id="test">
<option value="a">Item A</option>
<option value="b">Item B</option>
</select>
<br>
<button type="button" id="bid">test</button>
JavaScript
$(function() {
$("#bid").click(function() {
$("#test option").each(function(ind, el) {
console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
});
});
});
The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.

Related

Disable an option from a selection by its value

I'm trying to disable an option from a selection through its value. When the value is equal to 'sure' the option is available. When the option is 'wrong' let it be disabled for options.
$(document).ready(function() {
$.getJSON("https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
$.each(result.values, function(i, field) {
$("#SelectTestID").append('<option hidden="hidden" selected="selected" value="">Options</option><option value="' + field[1] + '">' + field[0] + '</option>');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<select class="SelectTest" id="SelectTestID"></select>
If I've understood what you're asking you can check the value of field[1] and set the disabled property of the option element accordingly.
Also note that in the example below I remove the hidden option element as it served no purpose, and I also used a template literal for building the string as it's easier to read and less verbose.
$(document).ready(function() {
$.getJSON("https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
$.each(result.values, function(i, field) {
$("#SelectTestID").append(`<option value="${field[1]}" ${(field[1] === 'wrong' ? 'disabled' : '')}>${field[0]}</option>`);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<select class="SelectTest" id="SelectTestID"></select>
In the current example you can do so by checking if field[1] is equal to "wrong", if it is then you add the disabled="true" attribute to the option.
Here's an example of what that might look like:
$(document).ready(function () {
$.getJSON(
"https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI",
function (result) {
$.each(result.values, function (i, field) {
let optionString = `<option hidden="hidden" selected="selected" value="">Options</option><option value="${field[1]}">${field[0]}</option>`;
if (field[1] === "wrong") {
optionString = `<option hidden="hidden" selected="selected" value="">Options</option><option value="${field[1]}" disabled="true">${field[0]}</option>`;
}
$("#SelectTestID").append(optionString);
});
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="SelectTestID">
</select>
There are other approaches you could use, but since you're already using a string to append your Select element I used a string as well.

Removing an option based on text instead of value

I want to remove an option from an select based on the text of the option.
I tried using this line of code:
$('#list_' + id + ' option[text="' + alias + '"]').remove();
Sadly this doesn't work for me, as it removes nothing. If I use value instead of text it works, but I was wondering how I can do this using text.
// Removing based on text doesnt work.
$('.removeByText').click(function() {
$('#list option[text="Option2"]').remove();
});
// Removing based on value works.
$('.removeByValue').click(function() {
$('#list option[value="2"]').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='list'>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
<option value='4'>Option4</option>
</select>
<button class='removeByText'>removeByText</button>
<button class='removeByValue'>removeByValue</button>
option elements don't have a text attribute. If you want to do it this way, you could use :contains:
$("#list_" + id + " option:contains(" + alias + ")").remove();
...but that does a substring match. Probably you'll want to filter:
$("#list_" + id + " option")
.filter(function() {
return this.textContent === alias;
})
.remove();
Live Example using filter:
setTimeout(() => {
const id = "example";
const alias = "B";
console.log(`Removing '${alias}'...`);
$("#list_" + id + " option")
.filter(function() {
return this.textContent === alias;
})
.remove();
}, 800);
<select id="list_example" size="3">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Using selector to replace all dropdownlist (select) with label

I'm trying to replace all the drop down lists with a p element or a label that have only the selected option, reason is I want to prepare this for printing without showing the down arrow that is in dropdownlist.
I need to use type selector as the select element have different classes name and no IDs. Problem is I can't seem to get the complete select element when I'm using $("select").
I notice when I use $("select") I got different results than using the ID selector in console
$("#id") //return
init {context: document, selector: "#2"}
var allInputs = $("select"); //return
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
allInputs[key].replaceWith("<p>" + text+ "</p>") //so this doesn't work
Here's a copy of the JS code
var allInputs = $("select");
if($("#2")==allInputs[0])
{alert("True");}
$.each( allInputs, function(key, value ) {
var text=value.find("option:selected").text() ;
allInputs[key].replaceWith("<p>" + text+ "</p>");
});
Jsfiddle here:
https://jsfiddle.net/abahrani/fzhv41s7/4/
how about use mapping (I did it with an unordered list but you get the idea) run the snippet below
$('#mybutton').click(function() {
$("select").map(function() {
return $(this)
}).get()
.forEach(function(element) {
$('#container').append(
`<ul><li>
${element.val()}<ul>${getOptions(element)}</ul>
</li></ul>`)
});
function getOptions(element) {
let html = ''
element.find('option').map(function() {
return $(this).val();
}).get()
.forEach(function(option) {
html += `<li>${option}</li>`
});
return html;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file">
<input type="text">
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
<select>
<option>selector</option>
<option>Option3</option>
</select>
</br>
<button type="button" id="mybutton">
print all options
</button>
</form>
<div id="container">
</div>
As per thmsdnnr comment, I found out the reason
allInputs[key].replaceWith("<p>" + text+ "</p>") // doesn't work
didn't work because I needed to use the $ sign, when $(allInputs[key]) used. everything worked.
$(allInputs[key]).replaceWith("<p>" + text+ "</p>") //works

Jquery on button click get the selected option value

I have this code below. Trying to get the value of selected option but first one give error that test.parent is not a function and second variable get an empty string. How can I make this work?
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" onclick="addItem(this)" type="button">
<script>
function addItem(test){
var selected_val1 = test.parent('#gender option:selected').val();
var selected_val2 = $("#gender option:selected").text();
}
</script>
You're passing this to the addItem() function, and caching it as test, and that's not a jQuery object, but a native DOM node.
Then you're doing test.parent('#gender option:selected').val();, but test had no parent method, nor does it have a parent select element.
The select is the previous element, so you should be using prev
$(test).prev('[name="gender"]').find('option:selected').val();
or just
$(test).prev('select').val();
seems easier
var selected_val1 = $(test).parent().find('select[name="gender"] option:selected').val();
Here's an example: http://jsfiddle.net/z96c7025/
Inline JS is not recommended, so I would go with something like:
$('#mybutton').on('click', addItem);
function addItem() {
//in this callback 'this' refers to the button that was clicked and,
//as #adeneo has rightly pointed out, it should be wrapped in $()
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
$('#mybutton').on('click', addItem);
function addItem() {
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" type="button" id="mybutton">
As others have said, inline JS is not always a good choice, but if you choose to do so, these modifications should help. The javascript can be much, much more simple.
HTML
<form>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input value="Submit" onclick="addItem(this.form)" type="button"> </form>
</form>
JS
function addItem(form) {
console.log(form.gender.value)
}
JS Extended
function addItem(form) {
var gender = form.gender;
for ( var i=0; i<gender.length; i++) {
console.log('Option ' + i + ': ' + form.gender[i].value)
}
console.log('Selected option: ' + form.gender.value);
var unselectedIndex = ( form.gender.selectedIndex + (form.length - 1))
console.log('Unselected option: ' + form.gender[unselectedIndex].value)
}

ddslike get two values from diffrentes select

i have little problem with ddslike jquery lib
I have two select box like this:
<select id="from">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
<select id="to">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
Javascript of SELECT BOX (Want just the design from ddslike):
<script type="text/javascript">
$(document).ready(function () {
$('#from_fees').ddslick({
width: 100,
});
$('#to_fees').ddslick({
width: 100,
});
});
</script>
Here my script that i wanted to fetch value of select's options:
$(function(){
$("#from").change(function(event){
//alert("Click event on Select has occurred!");
$("option:selected", $(this)).each(function(){
var obj = document.getElementById('from').value;
alert("selected value"+obj);
});
});
});
But i get no results !
I want get the two value from the two select in the same time.
Thank you.
First, you've got to be consistent with your IDs. You've got id="from" in the html, but you call .ddslick() on the element with id "from_fees".
If I understand, you'd like to get the values of each whenever either one changes. How about:
<script>
$('select').change(function(){
var to = $('#to').val();
var from = $('#from').val();
// alert("To: " + to + " and from: " + from + ".");
});
</script>
You don't need to use "this", because you want the value out of both of them.

Categories

Resources