How to get value from select using javascript - javascript

$(document).on('click', '.product_quantity_up', function(e){
var valueFromForm;
valueFromForm = document.getElementById("group_2").value;
e.preventDefault();
fieldName = $(this).data('field-qty');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!allowBuyWhenOutOfStock && quantityAvailable > 0)
quantityAvailableT = quantityAvailable;
else
quantityAvailableT = 100000000;
if (!isNaN(currentVal) && currentVal < quantityAvailableT)
$('input[name='+fieldName+']').val(currentVal + valueFromForm).trigger('keyup');
else
$('input[name='+fieldName+']').val(quantityAvailableT);
$('#quantity_wanted').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select name="group_2" id="group_2" class="form-control attribute_select no-print"> <option value="18" selected="selected" title="35">35</option>
<option value="19" title="36">36</option>
<option value="20" title="37">37</option>
<option value="21" title="38">38</option>
<option value="22" title="39">39</option>
<option value="23" title="40">40</option>
</select>
I have a drop down list and I want to get value. Next, add this value into quantity.
Look at valueFromForm variable. And this is a Prestashop 1.6 where I want to use it. To test this code You can choose "Size" attribute.
Thanks for help.

To get selected use $('#group_2 :selected').val();
you are making your code a little more complicated
why use vanilla JS like document.getElementById("group_2").value; inside Jquery ??

I have placed some changers to your code but I have no idea what are the following values,
allowBuyWhenOutOfStock
quantityAvailable
fieldName
now the code is ruining try it
$(document).ready(function() {
var allowBuyWhenOutOfStock = true
var quantityAvailable = 100
$(document).change(function(e) {
var valueFromForm;
valueFromForm = document.getElementById("group_2").value;
e.preventDefault();
fieldName = $(this).data('field-qty');
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
if (!allowBuyWhenOutOfStock && quantityAvailable > 0) {
quantityAvailableT = quantityAvailable;
} else {
quantityAvailableT = 100000000;
}
if (!isNaN(currentVal) && currentVal < quantityAvailableT) {
$('input[name=' + fieldName + ']').val(currentVal + valueFromForm).trigger('keyup');
} else {
console.log(fieldName + " " + quantityAvailableT)
$('input[name=' + fieldName + ']').val(quantityAvailableT);
}
$('#quantity_wanted').change();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select name="group_2" id="group_2" class="form-control attribute_select no-print">
<option value="18" selected="selected"title="35">35</option>
<option value="19" title="36">36</option>
<option value="20" title="37">37</option>
<option value="21" title="38">38</option>
<option value="22" title="39">39</option>
<option value="23" title="40">40</option>
</select>

Please check out this jsBin to see how the get should work in your case:
JsBin example
But after all:
get value of a select element: $("#group_2").val();
get text of the selected option: $("#group_2").find("option:selected").text();
get other attributes of the selected option: $("#group_2").find("option:selected").attr("title");
In your case:
var valueFromForm = $("#group_2").val();
I can also suggest to check the "keyUp" event that is attached to the input field becasue the end of your jQuery chain there is this: .trigger('keyup')

Related

jQuery multiple select change event can't get option values in order of selection

I want to stock multiples choices in a input hidden when I change my select (example I select the last option then the first option) I get in my input the same order .
$('select').change(function() {
var str = "";
// For multiple choice
$("select option:selected").each(function() {
str = $(this).val() + str + " ";
});
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
Now If I change for example
(BASTIEN test1/BASTIEN test2/BASTIEN test0)
when I run my code I get
(BASTIEN test0/BASTIEN test1/BASTIEN test2)
this my code work fine but when I select the last then the second the problem here Is when I select the third one they don't work and I don't get the value of my option inside my var
If I understood you correctly this may help:
Target options directly with click event and save them in order in array.
With e.target.selected ? you make sure push is made on selected only.
remove function will remove element from array if deselected.
var str = []
$('select#brands option').on("click", function(e) {
let l = $(e.target).parent().find("option:selected").length
console.clear()
if (l > 1) {
e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);
} else if (l === 1 && str.length != 2) {
str = [e.target.value]
} else if (l === 1 && str.length === 2) {
remove(str, e.target.value)
} else if (l === 0) {
str = []
}
console.log(str)
});
function remove(str, item) {
var index = str.indexOf(item);
if (index !== -1) {
str.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands" multiple="multiple">
<option value="1">BASTIEN test1</option>
<option value="2">BASTIEN test2</option>
<option value="3">BASTIEN test3</option>
<option value="4">BASTIEN test4</option>
</select>
Like this. When you select from the beginning, the options array is reset.
var str = "";
$('select').change(function() {
//alert($(this).find("option").length);
if($(this).find("option").length < str.split(" ").length){
str = "";
}
// For multiple choice
str = $(this).find("option:selected").val() + str + " ";
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>

Adding another option when the select dropdown is clicked?

I need to add a new select option in my HTML when they click it
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>
This new option is dynamic and will be coming from an API response... I'm parsing the var value from the API response but for now, I made it static just to test.
Right now, I have this:
$(document).ready(function () {
var k = 1
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var html = $(".statusButton").html();
if (k == 1) {
if (value == "Disable") {
new_v = "<option value='Disable' >Disable</option>";
}
else if (value == "Enable") {
new_v = "<option value='Enable' >Enable</option>"
}
var full = html + "" + new_v;
$(".statusButton").html(full);
k = 2;
}
});
});
It is working on JSFiddle but when I try to integrate it on my website, it's not reading it, even just the console log. WHat am I doing wrong?
I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).
Consider:
...
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var $statusButton = $(".statusButton");
if(k == 1){
if(value == "Disable")
{
$statusButton.append("<option value='Disable' >Disable</option>");
}
else if(value == "Enable")
{
$statusButton.append("<option value='Enable' >Enable</option>")
}
...
If you do things that way, you don't have to mess around with any extra .html calls.
This is short answer without creating too many variable.
$(document).ready(function() {
var k = 1
$(".statusButton").on('focus', function() {
var value = "Disable";
if (k == 1) {
if (value == "Disable") {
$(".statusButton").append("<option value='Disable' >Disable</option>");
} else if (value == "Enable") {
$(".statusButton").append("<option value='Enable' >Enable</option>")
}
k = 2;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>

The scripts that I made dont work and I can't find the problem

First of all, sorry, I know the next code is wrong, I'm new in programming and I have a problem with it. When the user select an option from the Select, a value it must change, then, the user must write a price in numbers which value must not be higher than the previous value, here is when the scripts should act but it doesn't works. The correct code must be something like that:
<script>
function cboc(){
var cb = $("#cbotipfon").val();
var maxvalGORE = null;
if(cb == 0){
maxvalGORE = 0;
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
}
function cbocc(){
var val = null;
var x = document.GetElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
document.GetElementById('txtprepos').value = "";
}
}
</script>
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon" onchange="cboc()">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" onblur="cbocc()" name="txtprepos" id="txtprepos"/>
I've been with that problem for days. If you can help me I'll be eternally grateful. Thanks in advance and for take your time.
Here is a simple example. No need to declare any function. Just declare your variables correctly and use the addEventListener method for getting the values of the input and select elements.
var maxvalGORE ,val ,cb ,x = null;
document.getElementById("cbotipfon").addEventListener("change", function(){
var cb = document.getElementById('cbotipfon').value;
if(cb == 0){
maxvalGORE = 0;
}
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
});
document.getElementById("txtprepos").addEventListener("change", function(){
x = document.getElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
} else if(val == maxvalGORE) {
alert('The value is equal to $' + maxvalGORE +'.');
} else {
alert('The value is lower than $' + maxvalGORE +'.');
}
document.getElementById('txtprepos').value = "";
});
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" name="txtprepos" id="txtprepos"/>

How to set bootstrap multiselect min selected and max selected value

I have a multiselect dropdown with 5 option. I want max 3 option a user can select at a time and min 1 option can be select at a time, how to do that?
my code is like that---
<select id="auditorview" multiple="multiple">
<option value="A1" >AHT</option>
<option value="A2" >Offers</option>
<option value="A3" >Handled</option>
<option value="A4" >Xyz</option>
<option value = "A5"> Abc</option>
</select>
<script type="text/javascript" >
$(document).ready(function () {
$('#auditorview').multiselect({
buttonWidth: '150px'
});
});
$('#auditorview').on('change',function(){
foo = $(this).val();
if (!$("#auditorview option:selected").length) {
$("#auditorview option[value='"+foo[0]+"']").prop('selected', 'selected');
}
if($("#auditorview option:selected").length===4){
alert("Please select max 3 option !!!");
$("#auditorview option [value selected='"+foo[2]+"']").prop('selected', `false);`
}
})
</script>
UPDATED: ( answer updated as per requirement )
HTML:
<select id="demo" multiple="multiple">
<option value="">SELECT OPTION(S)</option>
<option value="Option1">Option-1</option>
<option value="Option2">Option-2</option>
<option value="Option3">Option-3</option>
<option value="Option4">Option-4</option>
<option value="Option5">Option-5</option>
<option value="Option6">Option-6</option>
</select><br/><br/>
Message: <label id="msg"></label>
JS:
$(document).ready(function () {
$("#msg").text("Select atleast One Option");
$("#demo option").on('click', function () {
if ($("#demo option:selected").length > 3) {
$("#msg").text('select Max 3 option at a time');
} else {
$("#msg").text("you selected: " + $("#demo option:selected").length);
}
});
});
JSFiddle DEMO
Find the solution, it works perfect for me--
<select multiple id="s">
<option>Option 1
<option>Option 2
<option>Option 3
<option>Option 4
</select>
<script>
$(document).ready(function () {
$('#s').multiselect();
})
jQuery("#s").on("change", function(){
var selectedOptions = $('#s option:selected');
if ((selectedOptions.length >= 3) && (selectedOptions.length > 1) ) {
// Disable all other checkboxes.
var nonSelectedOptions = $('#s option').filter(function() {
return !$(this).is(':selected');
});
var dropdown = $('#s').siblings('.multiselect-container');
nonSelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else if(selectedOptions.length <= 1){
var SelectedOptions = $('#s option').filter(function() {
console.log("1 select")
return $(this).is(':selected');
});
var dropdown = $('#s').siblings('.multiselect-container');
SelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else {
// Enable all checkboxes.
var dropdown = $('#s').siblings('.multiselect-container');
$('#s option').each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
});
}
});

Drop down menu adds input fields with corresponding ID and label

With Javascript, I created a drop down menu that generates the number of input fields that the user's selection (1-6) dictates. But how do I make the newly generated input fields' IDs & labels correspond to their place-number in the list of input fields? I hope that makes sense. You'll see in my html I have [ brackets ] where I want the dynamically generated number to be.
html:
<ul>
<li>
<label for="id_NOU">Number of Units:</label>
<select name="NOU" id="id_NOA">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</li>
<li class="list">
<label>Unit []</label>
<input type="text" id="unit[]"></input>
</li>
</ul>
JavaScript:
$(window).load(function () {
$('#id_NOU').change(function () {
var total = $(this).val();
//remove all
$('.list').each(function (index) {
if (index != 0) $(this).remove();
});
//create new ones
for (var i = 2; i <= total; i++) {
$('.list:first').clone().appendTo('ul');
}
});
});
Thank you so much for your help! I love JSFiddles...
Perhaps a better implementation would be to copy last field only and on further change keep the rest of the list intact
here is the code
var counter = 1;
$(function(){
$("#id_NOA").on("change", function(){
var $ul = $(this).parent().parent();
var val = $(this).val();
while($ul.find(".list").length < val){
var $item = $ul.find(".list:last").clone();
$item.find("input").attr("id", "unit"+counter++);
$item.find("label").html("Unit "+counter);
$ul.append($item);
}
if($ul.find(".list").length >= val){
$ul.find(".list:gt("+(val-1)+")").remove();
counter = val;
}
});
});
here is a jsfiddle link http://jsfiddle.net/EN687/1/
Solution:
$(document).ready(function(){
$('#id_NOU').change(function () {
var total = $(this).val();
//remove all
$('.list').each(function (index) {
if (index != 0) $(this).remove();
});
//create new ones
for (var i = 2; i <= total; i++) {
element = $('.list:first').clone();
element.find('input').attr('id', 'unit' + i);
element.find('label').html('Unit ' + i);
element.appendTo('ul');
}
});
});
Working demo: http://jsfiddle.net/6VQDR/1/

Categories