get two option id in one function - javascript

I want calculate a sum with the selected ID so I get all ID in different var then call them by find() my code is not work :
$(window).load(function(){
function doStuff() {
var uone= $("#ud").children(":selected").attr("id") == 'a';
var utwo= $("#ud").children(":selected").attr("id") == 'b';
var uthree= $("#ud").children(":selected").attr("id") == 'c';
var bone= $("#bt").children(":selected").attr("id") == 'd';
var btwo= $("#bt").children(":selected").attr("id") == 'e';
var getValue;
if ($(uone).find(bone)) {
getvalue = 75;
}
if ($(uone).find(btwo)) {
getvalue = 70;
}
if ($(utwo).find(bone)) {
getvalue = 81;
}
if ($(uthree).find(bone)) {
getvalue = 79;
}
var shw = $('#inputamount').val();
var total = getvalue * shw ;
$(".totalop").html(total);
}
$("#inputamount").on('keyup', doStuff);
$("#ud").on('change', doStuff);
$("#bt").on('change', doStuff);
});
<select name="sucompn" id="ud">
<option id="a">a</option>
<option id="b">b</option>
<option id="c">c</option>
</select>
<select name="ducompn" id="bt">
<option id="d">d</option>
<option id="e">e</option>
</select>
<input autocomplete="off" name="inputamount" id="inputamount" value="" type="text">
<span id="ttotal"></span>
Actually I want to create a result users input and select based. Something like when user select 'a' and 'd' then 'input=1' so result come = 75 .It will change when user change any option or input .

You should use value attributes:
<select name="sucompn" id="ud">
<option value="1" id="a">a</option>
<option value="2" id="b">b</option>
<option value="3" id="c">c</option>
</select>
And then access it via jQuery:
var gvalue = $('#ud').val();
If you'd like to overwrite it with the selected value of the other select element, you could simply do the same for the other one and overwrite it:
var otherValue = $('#sd').val();
if (otherValue) gvalue = otherValue

Related

Get values from two select element and compare in another function

I'm trying to get two values from different select elements and access those elements outside a function.
function firstValue(){
var e = document.getElementById("val-selec");
var strUser = e.options[e.selectedIndex].text;
return strUser;
}
function secondValue(){
var e1 = document.getElementById("val-selec1");
var strUser1 = e.options[e.selectedIndex].text;
return strUser1;
}
if(firstValue() == "val1" && secondValue() == "val2"){
//do something
}
when I log my function it just returns the first value it does not change when you select another option. What would be a way I can compare values and to a certain thing
https://jsfiddle.net/v50wdnL1/1/ I included a jsfiddle
Not quite sure why the #onchange events are calling function that only return values and dont do any meaningful operations. Instead make them both call a compare function and in that compare function call your other function which return the values. Example below:
HTML:
<select name="val-select" id="val-selec" onchange="compare();">
<option value="" disabled selected>Select your option</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
<br>
<select name="val-select1" id="val-selec1" onchange="compare();">
<option value="" disabled selected>Select your option</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
JavaScript:
function firstValue(){
var e = document.getElementById("val-selec");
return e.value;
}
function secondValue(){
var e1 = document.getElementById("val-selec1");
return e1.value
}
function compare(){
var value1 = firstValue();
var value2 = secondValue();
console.log(value1 === value2);
}
ok so, I think your code fails because you have a typo (depending where you want to put that if(condition){do_something()}, you are trying to access e when you should access e1 in the function secondValue()
I think you can get away without declaring those functions for the values like so:
function my_action(){
let firstValue = document.querySelector('#val-selec').value;
let secondValue = document.querySelector('#val-selec1').value;
if(firstValue == "val1" && secondValue == "val2"){
//do something
}
}
and then execute that func when u change the select:
<select name="val-select" id="val-selec" onchange="my_action();">
I hope is useful

Javascript won't read from "select" in a form

I am trying to get my code to read a value based off the selected item from a select list in my form, but it says it's undefined. When I simply give the function a value and tell it to return the value, it reads, but won't take values from the form.
The following is the code I'm using
for the form (in html):
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost()">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
and the javascript reads
function calculateCost()
{
var orderPrice = getItemPrice();
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
function getItemPrice()
{
var itemPrice = 0;
var theForm = document.forms["orderForm"];
var selectedItem = theForm.elements["item"];
itemPrice = item_prices[selectedItem.value];
return itemPrice;
}
HTMLCollection.item() is method of HTML select element Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
theForm.elements["item"] will return function expression of the HTMLCollection.item and which is causing the undefined value as theForm.elements["item"] does not have property value
Either pass this in inline-event or use other id and name attribute to select element than item
function calculateCost(elem) {
var orderPrice = getItemPrice(elem.value);
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices = [];
item_prices["None"] = 0;
item_prices["Candlestick"] = 10;
item_prices["Bowl"] = 10;
item_prices["Burl_Bowl"] = 20;
item_prices["Clock"] = 15;
item_prices["Vase"] = 5;
item_prices["Pen"] = 2;
item_prices["Top"] = 1;
function getItemPrice(val) {
var itemPrice = 0;
itemPrice = item_prices[val];
return itemPrice;
}
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost(this)">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
Edit: Or just use getElementById => var selectedItem = document.getElementById('item'); to access the select element.Fiddle here
This entire operation could be simplified a bit as well.
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
EDIT, you should use an object here if you want to be correct.
item_prices = {
None: 0,
Candlestick: 10
};
// etc...
document.getElementById('item').addEventListener('change', function (event) {
document.getElementById('totalPrice').innerHTML = item_prices[event.target.value];
});

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

How to change selected menu option using jquery

Hi I am using jquery chosen plugin. I want to selected menu value by selected value from other select menu. But my code working with simple selected menu. I want it to work with jquery chosen plugin. Example code
$(".chzn-select").chosen()
$('[id*=second]').change(function(){
var val = $(this).find('option:selected').val()
if(val.toLowerCase()=='mr'){
$('[id*=gender]').find('option').eq(0).attr('selected', 'selected');
}
else{
$('[id*=gender]').find('option').eq(1).attr('selected', 'selected')
}
})
​
You should add value to the options and try to match those value onchange. See my implementation below and let me know if it works for you.
Edit: Added few lines to update the plugin selection.
DEMO: http://jsfiddle.net/vUkQg/3/
Note: Below method can relate any number of drop downs with just same class and value.(no change to the script) http://jsfiddle.net/vCE4Y/18/
HTML:
<select id="second" class="chzn-select" style="width:100px">
<option value="1"> mr</option>
<option value="2"> mrs</option>
</select>
<select id="gender" class="chzn-select" style="width:100px">
<option value="1"> male</option>
<option value="2"> female</option>
</select>
JS:
$(function() {
$(".chzn-select").chosen().change(function() {
var val = $(this).val();
$('.chzn-select').val(val);
$('.chzn-select').not(this).each(function () {
var $chzn = $('#' + this.id + '_chzn');
var $li = $chzn.find('li');
$li.removeClass('result-selected');
var selectedLi = $li.eq(val - 1);
selectedLi.addClass('result-selected');
$chzn.find('a.chzn-single span').html(selectedLi.html());
//update selected result in plugin
var $data = $(this).data('chosen');
$.each($data['results_data'], function (idx, el) {
if (idx == val-1) {
el.selected = true;
$data.result_single_selected = selectedLi;
} else {
el.selected = false;
}
});
});
});
});
Demo
I hope the below script does what you expect
$(".chzn-select").chosen();
$('[id*=second]').change(function(){
var val = $('div[id*=second]').find('li.result-selected').html().trim();
$('select[id*=gender]').find('option').removeAttr('selected');
$('div[id*=gender]').find('li.active-result').removeClass('result-selected');
var selectedValue = "";
if(val.toLowerCase()=='mr'){
selectedValue = $('div[id*=gender]').find('li.active-result').eq(0).addClass('result-selected').html();
$('select[id*=gender]').find('option').eq(0).attr('selected','selected');
} else {
selectedValue = $('div[id*=gender]').find('li.active-result').eq(1).addClass('result-selected').html();
$('select[id*=gender]').find('option').eq(1).attr('selected','selected');
}
$('div[id*=gender]').find('a.chzn-single span').html(selectedValue);
});
Use selectedIndex
eg:
document.getElementById('selectId').selectedIndex = 0;
//selectId - id of the select elem
<select id="selectId">
<option value="1" selected="selected">Male</option>
<option value="2">Female</option>
</select>
To get the Selected value
var e = document.getElementById("selectId");
var strUser = e.options[e.selectedIndex].value;
here strUser = 1;
if you want the TEXT
var strUser = e.options[e.selectedIndex].text;
here strUser = Male;
i think this helps you.
<select id="second" class="chzn-select" style="width: 100px">
<option value="1">mr</option>
<option value="2">mrs</option>
</select>
<select id="gender" class="chzn-select" style="width: 100px">
<option value="1">male</option>
<option value="2">female</option>
</select>​
$(document).ready(function () {
$('.chzn-select').change(function () {
$('.chzn-select').val($(this).val());
//$('.chzn-select').val($(this).val()).trigger('change');
});
});​
Demo
I used the value of the options, the minus 1 is to reach the indexnumber
DEMO
$('#second').change(function(){
var val = $(this).val();
$('#gender option').eq(val - 1).attr('selected', 'selected');
});
or
$('#second').change(function(){
var index = $(this)[0].selectedIndex;
$('#gender option').eq(index).attr('selected', 'selected');
});

Change style of text field based on the selection of a combo box using Javascript

I would like to change the style of a text field based on the value selected in a combo box. Specifically, what I'd like to do is make the txtDepartment field gray and marked as "read only" if the option value selected in cboSource is 1. I've tried the code below, but I imagine my style code at least is wrong, if not other things. Any help appreciated. Thanks!
<select name="cboSource" id="cboSource" onClick="displayDepartment(this);">
<option value = 1>Source 1</option>
<option value = 2>Source 2</option>
</select>
<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>
<script>
function displayDepartment(obj)
{
var selectedValue = obj.value;
var txtDepartment = document.getElementById("txtDepartment");
if (selectedValue == "1")
{
txtDepartment.style.display = "Disabled style='background-color:#E8E8E8'";
}
}
</script>
txtDepartment.style.backgroundColor = "#E8E8E8";
txtDepartment.disabled = 'disabled';
with jQuery your whole function gets a lot smaller:
function displayDepartment(obj)
{
if($(obj).value=="1") {
$("#txtDepartment").css('background-color','#E8E8E8');
$("#txtDepartment").disabled ='disabled'
}
}
First, use onchange on cboSource.
Then:
if(selectedValue == "1")
txtDepartment.disabled = 'disabled';
Set the disabled attribute for your element
// on
txtDepartment.setAttribute("disabled","disabled")
// off
txtDepartment.removeAttribute("disabled")
possible solution using jQuery:
<style>
.disabled {
background-color:#E8E8E8;
}
</style>
<script language="javascript">
$(document).ready(function() {
var txtDepartment = $("#txtDepartment");
var cboSource = $("#cboSource");
cboSource.change(function() {
txtDepartment.removeClass().removeAttr("disabled");
if (cboSource.val() == 1) {
txtDepartment.addClass("disabled").attr("disabled", true);
}
});
});
</script>
<select name="cboSource" id="cboSource">
<option value = 0>Choose</option>
<option value = 1>Source 1</option>
<option value = 2>Source 2</option>
</select>
<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>
In my opinion onclick is more suitable as on change has different meaning for different browser
Try this
<select name="cboSource" id="cboSource" onClick="displayDepartment(this);">
<option value = 1>Source 1</option>
<option value = 2>Source 2</option>
</select>
<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>
<script>
function displayDepartment(obj)
{
var txtDepartment = document.getElementById("txtDepartment");
txtDepartment.disabled = false;
txtDepartment.style = "";
if (obj.value == "1")
{
txtDepartment.style = "background-color:#E8E8E8";
txtDepartment.disabled = true;
}
}
</script>

Categories