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
Related
I found several topics here about removing items from a dropdown HTML element. However, when I try it, it fails from a script, but works in the console in browser.
The rest of the script works fine, and no errors are returned. First I have a variable with the item text, I let jQuery grab the corresponding value, and with that value I remove the item.
var topicToDelete = "topic3";
console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).val();
console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove(); //doesn't do anything
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
Executing the code directly doesn't work either:
$('#pick_topic option').filter(function () { return $(this).html() == topicToDelete; }).remove(); // nothing
However, when I enter the lines in the browser console line by line it works and the item is removed from the dropdown menu. How can this be?
I have also looked into this answer.
The issue is because you've put a # in the value of the id attribute, as a result your jQuery selector isn't matching anything. This should be removed.
var topicToDelete = "topic3";
//console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).val();
//console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic"> <!-- note: no # here -->
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
That being said, you're over-complicating the solution. filter() returns a jQuery object which you can remove directly. There's no need to get the value from that object, to then create another jQuery object pointing to the Element you already have access to. Try this:
var topicToDelete = "topic3";
$('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).remove();
// alternative, using :contains which is a greedy match:
// $('#pick_topic option:contains(' + topicToDelete + ')').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
Your code was good but remove # from id="pick_topic"
var topicToDelete = "topic3";
console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function () { return $(this).html() == topicToDelete; }).val();
console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
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.
How we can get the option HTML in jquery by it's value in jQuery.
HTML
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
Array
var id_arry = ['21','24','2'];
I have this array that have some values related to values in the drop down. Now i want to get all the options that matches the value in dropdown HTML
like
<option value="21">A</option><option value="24">D</option> <option value="2">E</option>
This is the final out put i want from the drop-down.Kindly help me in this
I want to add those options html in this dropdown:
<select multiple="" style="width: 147px;" id="list" name="list1" class="list_class">
</select>
Maybe something like this:
var id_arry = ['21','24','2'];
var optionMatches = $('#list option').filter(function() {
return $.inArray($(this).val(), id_arry);
});
Breaking it down:
$('#list option') - returns all of the options in the select list with ID "list"
.filter(callback) - a simple filter function -- the callback decides whether the option makes it into the final list
$.inArray($(this).val(), id_arry) - checks if the current option value is in the array id_arry
After studying your example, it looks like you'll first want to obtain the selected options from your multi-select drop-down list to build your id_arry, which is very easy:
var id_arry = $('#list').val();
Once you have these and the optionMatches array of elements, you can clone them over to a new drop-down:
optionMatches.clone().appendTo('#otherSelect');
One solution is using join and split:
var id_arry = ['21', '24', '2'];
$("#list").val(id_arry.join(',').split(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
You can use jQuery's attribute equals selector to target elements with a specific attribute value:
$( "option[value='21']" )
Using this selector and a simple loop, you can extract all the elements you need:
var elements = [];
var id_array = ['21','24','2'];
for ( index in id_array ){
var elem = $( "option[value='" + id_array[ index ] + "']" );
if ( elem ) {
elements.push( elem );
}
}
Your elements array now contains all option elements who's values appear in id_array.
var id_arr = ['21','24','2'];
var entireHTML = "";
var options = $('select').find('option');
var tempDiv = $('div');
//id_arr = $('select').val(); //Uncomment this line to get value from the select element.
$.each(id_arr, function(index, value){
entireHTML = "";
$(options).each(function(){
if( $(this).val() === value)
{
$(this).clone().appendTo(tempDiv);
}
});
});
entireHTML = $(tempDiv).html();
Since you need the HTML content of the 'option' elements, they're cloned and wrapped in a temporary div so that the inner HTML of that temporary div is copied and appended to our final HTML string.
Check it out for yourself : JSFiddle Test Link
I'm trying to fill a select list with the values entered in an input text box when the user clicks on a button. For eg:
HTML:
<form>
<h2>Add EVENT/MARKET/SELECTION ID </h2>
<select id="id_type">
<option value="sEVENT">Event</option>
<option value="sEVMKT">Market</option>
<option value="sSELCN">Selection</option>
</select>
<input id="entered_id" type="number"/>
<button id="add_id" onclick="populateList()">Add</button>
</form>
<form>
<h2>Entered IDs</h2>
<select id="list_id" size="10" multiple="true"></select>
</form>
JS:
function populateList() {
var events_id = document.getElementById('entered_id').value;
/*I want this events_id to be entered to the select list "list_id"*/
}
I tried $("#list_id").append(events_id) but that didn't work.
Any help is appreciated.
Thanks
since its <select> you need to append <option> tag, as:
$("#list_id").append("<option value='"+events_id+"'>"+events_id+"</option>");
Try FIDDLE
$("#add_id").click(function () {
var value = $("#entered_id").val();
$("#list_id").append("<option value =" + value + " >" + value + "</option>");
});
using JavaScript
var option = document.createElement("option");
option.text = document.getElementById('entered_id').value;
option.value = document.getElementById('entered_id').value;
var select = document.getElementById("list_id");
select.appendChild(option);
Doing everything the jQuery way you can bind a click handler to the button instead of the inline method.
$('#add_id').click(function() {
$('<option/>', { text: this.value }).appendTo('#list_id');
});
My current jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?
$('#trapfabric, #trapsize').on('change', function() {
var $selected = $('#trapfabric, #trapsize').children(":selected");
sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
$('#priceToSwap3').html('$' + sum
);
});
I know I have to fit something like this in the above but I can't get it to work:
$('#priceToSwap3').text($selected.data("price"))
EDITED
My HTML:
<span id="priceToSwap3"">$238</span>
<select id="trapsize" onChange="swapImage()">
<option data-price="238">foo</option>
<option data-price="288">foo</option>
</select>
<select id="trapfabric" onChange="swapImage()">
<option data-price="0">foo</option>
<option data-price="20">foo</option>
</select>
I believe this is what you want:
var $elements = $('#trapfabric, #trapsize');
$elements.on('change', function() {
var $selected = $elements.children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#priceToSwap3').html('$' + sum);
});
You have to iterate over the selected elements to get the price datum of each of them.
DEMO
You are binding event to two elements #trapsize, #trapfabric if you want to get the source element you need to use $(this);
jsfiddle
$('#trapfabric, #trapsize').on('change', function() {
$('#priceToSwap3').text( '$' + $(':selected', this).data("price") );
});
We had a similar scenario wherein we assign security value(1,2,3 as security level) for each input. We have to change the security values "0" when the user logs into the system.
Eg:
<input type="text" security="3" id="super-admin" />
<input type="text" security="2" id="main-admin" />
<input type="text" security="1" id="normal-user" />
<script>
function userValidation(userType){
if(userType="super-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
$("[security=3]").attr("security", 0);
}
if(userType="main-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
}
if(userType="normal-user"){
$("[security=1]").attr("security", 0);
}
}
<script>