Change select option based on attribute - javascript

I am trying to change a select option on click but I don't want to use the option value. My code works if I give my button a value='3' but what I want is to select the one with data-price="0" which in my case is the one with value='3'.
JS :
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option').val(jQuery(this).attr('value'));
});
});
Html :
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
Any help will be appreciated

You can use attribute equals selector to get the option and then select option by setting selected property using prop() method.
jQuery(document).ready(function() {
jQuery('#sample-addtocart-button').click(function() {
jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>

You can select elements by attribute, and then set the selected property on the element.
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
});
});
This selects the element with a data-price attribute equal to the value of this.value, which is a descendant of .product-custom-option, and sets its selected property to true.
Without jQuery, it could look like this:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
And a handful of helper methods always helps with the verbosity:
function listen(el, typ, fn, cap) {
el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
if (typeof el === "string") {
sel = el;
el = document;
}
return el.querySelector(sel)
}
listen(document, "DOMContentLoaded", function () {
listen(query('#sample-addtocart-button'), "click", function(){
query('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});

Try this:
jQuery('#sample-addtocart-button').click(function(){
var val= jQuery(this).attr('value');
jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});

Related

Append options with multiple select into simple select

I'm using multiple select for fill a simple select. I'm trying to if I select a value and it doesn´t exists append to simple select, if exists do not do anything, but if I unselect option, remove it from simple select. How could I do that?
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val();
values.forEach(function(val) {
$('#bar option').each(function() {
var v = $(this).val();
if (values.indexOf(v) === -1) {
$('#bar').append('<option value="' + val + '">' + val + '</option>');
return false;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
Remove all options except the disabled one from #bar after #foo changed and create new options and appendTo() #bar.
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val() || []; // in case you don't select anything
$('#bar option:not(:disabled)').remove()
values.forEach(function(val) {
$('<option>', {
value: val,
text: val
}).appendTo('#bar')
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
You have to empty the children upon every change or else the new <option>s will get appended and the list becomes very long. Try this:
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val();
$('#bar').empty().append('<option selected disabled>Add some from multiple</option>');
values.forEach(function(val) {
$('#bar option').each(function() {
var v = $(this).val();
if (values.indexOf(v) === -1) {
$('#bar').append('<option value="' + val + '">' + val + '</option>');
return false;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
You should bind click event rather than change, because if you click same option twice, change event cannot be listened.
You can try the following code.
$(function() {
//get onclick value
$(document).on('click', '#foo', function() {
let value = $(this).val();
//get existing values in #bar
let exist = false;
$("#bar option").each(function(){
if($(this).val() == value){
exist = true;
//remove if exist
$(this).remove();
}
});
//append if not exist
if(!exist){
$('#bar').append(`<option value="${value}">${value}</option>`);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled value="default">Add some from multiple</option>
</select>
Well you're going to have more problems than this I think, but if you're just looking how to remove an option, you could do something like this
$("#bar option([value=" + val+ "]").remove();

Jquery filter is not working as expected

<div id="div1">
<input id="input1">
<select multiple="multiple" id="select1">
<option value="sandeep">sandeep</option>
<option value="ram">ram</option>
<option value="raj">raj</option>
<option value="pak">pak</option>
<option value="abc">abc</option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="journey">journey</option>
<option value="mahesh">mahesh</option>
</select>
</div>
<script type="text/javascript">
var selectClone1;
selectClone1 = $('#select1 option').clone();
$('#input1').on('keyup', function(){
$('#select1 option').remove();
var value = $(this).val();
selectClone1.filter(function(index, element){
console.log('index : '+index);
console.log('element : '+element);
return value == '' || element.value.indexOf(value) >= 0;
}).appendTo('#select1');
});
$('#select1').on('click', function(){
var option = $('option:selected', this).clone();
$('option:selected', this).remove();
selectClone1 = $.grep(selectClone1, function(el){return el.value == option[0].value}, true);
</script>
I am working on the search functionality along with removal of options when user clicked on option. The above code is working properly for search but when i clicked an option to delete from select box after search for a value, parameters of filter function(index, element) getting exchanged. Due to it error is coming. Can you help me guys where i am missing the point.
Better to use Array's splice method for removing element from main array and no need to clone.
$('#select1').on('click', function(){
var option = $('option:selected', this);
$('option:selected', this).remove();
selectClone1.splice($.inArray( option[0], selectClone1 ), 1);
});

Using jQuery to check and see if a select box has/or contains selected options

Using jQuery, upon a change/select event, how can I check and see if multiple select boxes contain any selected items? All I am looking for is how to capture and obtain a total count of this?
Based on a validation if not equal to 0, this would set a buttons default disabled attribute to false.
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
</form>
$('#myform select).bind("change select",function() {
});
Assuming your <button> is within the form element, the following should work for you:
// binding the anonymous function of the on() method
// as the event-handler for the 'change' event:
$('#myform').on('change', function() {
// caching the $(this) (the <form>, in this case):
var form = $(this);
// finding the <button> element(s) within the <form>
// (note that a more specific selector would be
// preferable), and updating the 'disabled' property,
// finding all <option> elements that are selected,
// filtering that collection:
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
// retaining only those whose values have a length
// (in order to not-count the default 'empty'
// <option> elements:
return this.value.length;
// and then checking if that collection is
// equal to 0, to obtain a Boolean true
// disabling the <button>, or a false to
// enable the <button>:
}).length === 0);
// triggering the change event on page-load
// to appropriately enable/disable the <button>:
}).change();
$('#myform').on('change', function() {
var form = $(this);
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
return this.value.length;
}).length === 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<button>Submission button</button>
</form>
References:
change().
filter().
find().
on().
prop().
You can use the jQuery :checked selector to capture all elements that are checked. For the count, you can do:
$( "input:checked" ).length;
You can then do your condition to view if there are zero or more elements checked:
var selected = $( "input:checked" ).length;
if(selected > 0)
//do something
$('#myform select').on('change', function() {
var count = 0;
$('#myform').find('select').find('option').each(function(){
if ($(this).is(':selected')){
count++;
}
});
if (count < 0){
$('#mybutton').prop('disabled', false);
} else {
$('#mybutton').prop('disabled', true);
});
Grab all the selects on the page and just loop through them while adding a change event to each one.
Then in that change event, call a method that counts up how many selects have items selected.
https://jsfiddle.net/x833qr20/3/
// put an on change event on all the selects, can be done in onload
var ddl = $('select');
for (i = 0; i < ddl.length; i++) {
ddl[i].onchange = function() {
CountAllSelectedDDL();
}
}
// function that fires when one select gets changed
function CountAllSelectedDDL() {
var ddl = $('select');
var count = 0;
for (i = 0; i < ddl.length; i++) {
if (ddl[i].selectedIndex > 0) {
count++;
}
}
var button = document.getElementById('button');
if (count > 0) {
// set the buttons default disabled attribute to false
button.disabled = false;
} else {
button.disabled = true;
}
}
Hope this helps.
Here's a working example via jQuery
https://jsfiddle.net/wedh87bm/
$('#myform select').bind("change select",function() {
var completed = true;
$('#myform select').each(function(){
if($(this).val() == "")
{
completed = false;
}
});
if(completed)
{
$('#validate').prop("disabled",false);
} else
{
$('#validate').prop("disabled",true);
}
});

Set attribute to readonly when dropdown value is changed

I have this dropdown that has 4 options.
What I want to achieve is to change the attribute of input text number to readonly when a user selects option3 or option4 from the dropdown.
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" name="number">
This is the script that I have for now, what it does is just alert the selected value.
$(document).ready(function () {
$("#s_id").change(function () {
var x = $(this).val();
alert($(this).val());
if (x == opel) {
alert("iff");
$(this).attr("readOnly", "true");
}
});
});
JS Fiddle link
Any idea/s would be really appreciated!
Use prop to make readonly and remove it back
DEMO
$(document).ready(function () {
$("#s_id").change(function () {
if (this.value === 'option3' || this.value === 'option4')
$("input[name='number']").prop('readonly', true);
else
$("input[name='number']").prop('readonly', false);//enable it back again
});
});
You can simply check your .value in your change handler and use jQuery .prop method:
$("#s_id").change(function () {
var isReadonly = (this.value === 'option3' || this.value === 'option4');
$("input[name='number']").prop('readonly', isReadonly);
});
or using an array for making it easier to modify it in future:
$("#s_id").change(function () {
var isReadonly = ['option3', 'option4'].indexOf(this.value) > -1;
$("input[name='number']").prop('readonly', isReadonly);
});
Here is the working JSFiddle demo.
Use prop() to set the readonly property of the text-box.
Create an array of all the values of the drop-down which, when selected, the number text-box should be disabled.
Check if the selected value is in the array in the change event handler
If the selected option value is present in the array, disable the number text-box, else enable it
Demo
$(document).ready(function() {
// Values when selected, the number box should be disabled
var values = ['option2', 'option3'];
// On selection change of the dropdown
$("#s_id").change(function() {
// values.indexOf($(this).val()) > -1
// Checks if the value selected is from the array
// Comparison returns true when the value is in array, false otherwise
$('input[name="number"]').prop('readonly', values.indexOf($(this).val()) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number:
<input type="text" name="number">
Try following code :-
$(this).attr("disabled", true);
I think drop down is always read only . what you can do is make it disabled
if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value
Please use this, You can also use it dynamically
Given below the HTML code
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" id="number" name="number">
Given below the JQuery code
$(document).ready(function () {
$("#s_id").change(function () {
var option_Array = ["option3","option4"]
var x = $(this).val();
$("#number").prop('readonly', false);
for(var i=0; i<option_Array.length; i++){
if (x == option_Array[i]){
$("#number").prop('readonly', true);
}
}
});
});

Disable a specific option boostrap-multiselect

Question
I want to disable a single option with JS. I tried using the following code:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
It kind of works, but the problem is I can still enable the option using the Select all button.
Also, not sure if relevant, I execute the code in a onChange from a different multiselect.
<select id="sel_secLang" multiple="multiple">
<option value="nlSec" disabled="disabled">Dutch</option>
<option value="enSec">English</option>
<option value="deSec">German</option>
<option value="FrSec">French</option>
</select>
Hope this explanation is clear enough, first question ;D.
Answer
Although Joe's answer worked I tried it out myself, For disabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', true);
var input2 = input.parent('label').parent('a').parent('li');
input4.removeClass('active');
input4.addClass('disabled');
For enabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
var input2 = input.parent('label').parent('a').parent('li');
input2.removeClass('disabled');
Just the value of the input
selectedPriLang = $('#sel_priLang option:selected').val();
Just a quick note to clarify: disabling the corresponding checkbox and adding the .disabled class to the appropriate li is not sufficient. You also have to disable the underlying option. Example (can also be found in the documentation):
<script type="text/javascript">
$(document).ready(function() {
$('#example-disable-javascript').multiselect({
includeSelectAllOption: true
});
$('#example-disable-javascript-disable').on('click', function() {
var input = $('#example-disable-javascript-container input[value="3"]');
var option = $('#example-disable-javascript-container option[value="3"]');
input.prop('disabled', true);
option.prop('disabled', true);
input.parent('label').parent('a').parent('li').addClass('disabled');
});
$('#example-disable-javascript-check').on('click', function() {
var options = '';
$('#example-disable-javascript option:selected').each(function() {
options += $(this).val() + ', ';
});
alert(options.substr(0, options.length - 2));
});
});
</script>
<div class="btn-group" id="example-disable-javascript-container">
<select id="example-disable-javascript" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
<button id="example-disable-javascript-disable" class="btn btn-primary">Disable an option!</button>
<button id="example-disable-javascript-check" class="btn btn-primary">Check</button>
</div>
You'll have to process the disabled events in an on-change handler on you're own and de-select them when the select-all is picked. Generally the process could look like:
Capture on selection event for select all
Iterate on elements
Remove the checked attribute for the disabled elements
Something along the lines of capturing on change, find disabled, and unchecking them:
$('#sel_secLang').multiselect({
onChange: function(option, checked, select) {
$('input[type=checkbox]:disabled').each(checkbox, function(){
checkbox.attr('checked', false);
});
}
});

Categories