I have a simple jquery calculator:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input">
Javascript:
$(document).ready(function () {
$('.price-option').change(function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
});
});
This calculator is working, but the problem is when I enter value for text input the result in price is not updating dynamically (I need to choose another option in selector for result updating)
You have to add keyUp event
calculate = function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}
$(document).ready(function () {
$('#price-option-input', .price-option').change(calculate);
$('#price-option-input', .price-option').keyup(calculate);
});
I think it´s worth it to explain that change event is fired when you unselect the input, or, in number type, when you use the up/down buttons.
You can add a button to do the computation, triggering the change event.
Example:
$("button").on("click", function() {
$('.price-option').trigger("change");
});
Or, you can listen the keyup event from the input and at the enter key press, do the computation. The question is: when do you want to do the computation? With the answer, listen to the proper event and do the computation.
I believe you just need to use .html because that will set the inner HTML:
$('.price span').html(price);
And for future reference, multi-selectors like that aren't near as efficient as something like this:
$('.price').find('span').html(price);
I have fixed your code and it works fine now http://plnkr.co/edit/pWSEimrKkA200jQK9w5a?p=preview
HTML:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input" onchange='updatePrice()'>
JS:
function updatePrice(){
var price = parseInt($('.price').data('base-price'));
console.log(price);
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}
Related
I'm having some html which is generated automatically, so I can't change it in the html directly. But it's basically this:
<select name="field2" id="id_18_gen" >
<option value="{1,2}" >Please choose...</option>
<option value="1" >correct</option>
<option value="2" >false</option>
</select>
Now I would like to add the hidden and the disabled attribute to the first option:
<option value="{1,2}" hidden disabled >Please choose...</option>
I've tried several things for example:
let e = document.getElementById(element);
e.options["{1,2}"].hidden ="true";
or
$("#" +element+ "option[value=" + "{1,2}" + "]").hide();
But nothing worked. A javascript or Jquery solution would be great, but css would be alright too.
check if the below code works
let e = document.getElementbyId('id_18_gen').firstElementChild;
e.disabled = true;
e.style.visibility = 'hidden';
Use setAttribute() method.
firstop.setAttribute("hidden","");
firstop.setAttribute("disabled","");
var firstop = document.querySelector("#id_18_gen option:first-child");
firstop.setAttribute("hidden","");
firstop.setAttribute("disabled","");
<select name="field2" id="id_18_gen" >
<option value="{1,2}" >Please choose...</option>
<option value="1" >correct</option>
<option value="2" >false</option>
</select>
e.setAttribute('attribute', value).
To select an specific option, it's e.options[index] or e.options.item(index) (the same) or by it's id width e.options.namedItem(id).setAttribute(....)
To find a specific option by value:
e.options.map((option, index) => {
if (option.value == '{1,2}')
option.setAttribute('hidden', true);
})
or better with queryselector:
document.querySelector('#id_18_gen option[value={1,2}]')
In jQuery, you can use:
$('#id_18_gen option').first().attr({"hidden":"","disabled":""});
$(function() {
const firstOpt = $('#id_18_gen option').first();
console.log( "Before:", firstOpt[0] );
firstOpt.attr({"hidden":"","disabled":""});
console.log( "After:", firstOpt[0] );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="field2" id="id_18_gen" >
<option value="{1,2}" >Please choose...</option>
<option value="1" >correct</option>
<option value="2" >false</option>
</select>
I need to add some values from a HTML5 DataList to a <select multiple> control just with Javascript. But I can't guess how to do it.
This is what I have tried:
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option label="Red" value="1">
<option label="Yellow" value="2">
<option label="Green" value="3">
<option label="Blue" value="4">
</datalist>
<button type="button" onclick="AddValue(document.getElementById('AllColors').value, document.getElementById('AllColors').text);">Add</button>
<select id="Colors" size="3" multiple></select>
function AddValue(Value, Text){
//Value and Text are empty!
var option=document.createElement("option");
option.value=Value;
option.text=Text;
document.getElementById('Colors').appendChild(option);
}
This should work. I have moved the value selection logic into the method itself.
You will only get the value from the input. You will need to use the value to select the label from the datalist.
function AddValue(){
const Value = document.querySelector('#SelectColor').value;
if(!Value) return;
const Text = document.querySelector('option[value="' + Value + '"]').label;
const option=document.createElement("option");
option.value=Value;
option.text=Text;
document.getElementById('Colors').appendChild(option);
}
Here is the working demo.
You can check the trimmed value of the input. If value is not empty then you can get the selected data list option by matching the value attribute with querySelector().
Try the following way:
function AddValue(el, dl){
if(el.value.trim() != ''){
var opSelected = dl.querySelector(`[value="${el.value}"]`);
var option = document.createElement("option");
option.value = opSelected.value;
option.text = opSelected.getAttribute('label');
document.getElementById('Colors').appendChild(option);
}
}
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option label="Red" value="1"></option>
<option label="Yellow" value="2"></option>
<option label="Green" value="3"></option>
<option label="Blue" value="4"></option>
</datalist>
<button type="button" onclick="AddValue(document.getElementById('SelectColor'), document.getElementById('AllColors'));">Add</button>
<select id="Colors" size="3" multiple></select>
To get the selected options's ID in datalist, you can use this code too.
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option value="Red" id=1></option>
<option value="Yellow" id=2></option>
<option value="Green" id=3></option>
<option value="Blue" id=4></option>
</datalist>
<script>
$("#SelectColor").change(function(){
var el=$("#SelectColor")[0]; //used [0] is to get HTML DOM not jquery Object
var dl=$("#AllColors")[0];
if(el.value.trim() != ''){
var opSelected = dl.querySelector(`[value="${el.value}"]`);
alert(opSelected.getAttribute('id'));
}
});
</script>
i am trying to find SUM of some number based on check box and select option .
here is my code
<div class="container">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>
<input type="checkbox" value="10">10
</label>
</div>
<input id="total" placeholder="total" />
And my script is
function updateTotal(){
var total = 0;
$(".container input[type='checkbox']").each(function(){
if($(this).is(":checked")){
var multiplier = Number($(this).parent().prev().val());
var checkboxAmount = Number($(this).val());
total += multiplier * checkboxAmount;
}
});
$("#total").val(total);
}
$("select, input[type='checkbox']").on("change", updateTotal);
The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output
i wanted my HTML code like this , then script should be work fine for this
<div class="container">
<label>
<input type="checkbox" value="10">10
</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<input id="total" placeholder="total" />
any help , code coppied from here
Try this one-
function updateTotal() {
var total = 0;
$(".container").each(function () {
var checkbox = $(this).find("input[type='checkbox']");
var select = $(this).find("select");
if (checkbox.is(":checked")) {
total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val());
}
});
}
I have an Adobe form that will allow my customers to select services by inputting their initials. How do I get the "total" field to show the total price for the services selected based on the user's selection using JavaScript?
I.E.: I have 3 optional services that a customer can select (one has to be selected, the other to are optional add-ons).
If I understand your question, you want to have an input that store the total price of selected services. So try something like this:
var service1 = document.querySelector('#service1');
var service2 = document.querySelector('#service2');
var total = document.querySelector('#total');
service1.addEventListener('change', function (e) {
var currentPrice = service1.options[service1.selectedIndex].getAttribute('data-price');
var service2Price = service2.options[service2.selectedIndex].getAttribute('data-price');
total.value = parseInt(currentPrice) + parseInt(service2Price);
});
service2.addEventListener('change', function (e) {
var currentPrice = service2.options[service2.selectedIndex].getAttribute('data-price');
var service1Price = service1.options[service1.selectedIndex].getAttribute('data-price');
total.value = parseInt(currentPrice) + parseInt(service1Price);
});
<select id="service1">
<option value="1" data-price="50">Service 1</option>
<option value="2" data-price="100">Service 2</option>
<option value="3" data-price="150">Service 3</option>
</select>
<select id="service2">
<option value="1" data-price="25">Service 1</option>
<option value="2" data-price="75">Service 2</option>
<option value="3" data-price="125">Service 3</option>
</select>
<input type="number" placeholder="Total" id="total" />
I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().
How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
The above example gets you the selected value of combo box on OnChange event.
Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:
function myFunction(chosen) {
console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
JavaScript Solution
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
I found #Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.
jQuery solution
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
See also
.val() jQuery API Documentation
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
Html template:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js code:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
function setMyValue(v) {
console.log(v);
}
<select onchange="setMyValue(this.value)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
This worked for me onchange = setLocation($(this).val())
Here.
#Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Simply:
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve_other() {
alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve() { alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
<p>RETRIEVING TEXT IN OPTION OF SELECT </p>
<form name="myForm" action="">
<P>Select:
<select id="SMS_recipient">
<options value='+15121234567'>Andrew</option>
<options value='+15121234568'>Klaus</option>
</select>
</p>
<p>
<!-- Note: Despite the script engine complaining about it the code works!-->
<input type="button" onclick="retrieve()" value="Try it" />
<input type="button" onclick="retrieve_other()" value="Try Form" />
</p>
</form>
</HTML>
</BODY>
Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value
//html code
<select onchange="get(this)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
//javscript code
function get(select) {
let value = select.value;
console.log(value);
}