Display text according to the selected option - javascript

I have an option for users to select if 'Yes' or 'No'. If options selected values 'y' text box 'adv1' displays 750. If else it is 0.00
<table>
<tr>
<td>Advance Required</td>
<td><select name="advReq" id="ad">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
</td>
<td><input name="adv1" type="text" readonly="readonly" value="" /></td>
</tr>
</table>

<script>
function updateText(val) {
var $el = document.getElementById("adv1");
if(val == 'y'){
$el.value = "$ 750";
} else {
$el.value = "0";
}
}
</script>
<select name="advReq" id="ad" onchange="updateText(this.value)">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<input name="adv1" type="text" id="adv1" value="" />

You can achieve this by using a simple JavaScript.
HTML Markup :
<select name="advReq" id="ad" onchange="changeValue(this.value)">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<input name="adv1" type="text" id="adv" value="" />
JavaScript :
function changeValue(val){
//use comparison operator
if(val=="y")
document.getElementById('adv').value = "$ 750";
else
document.getElementById('adv').value = "0.00";
}
If you wish to change the value dynamically with values from Server at real time. You can do it by using AJAX calls.

Related

Concatenate user input in Html form and assigning an ID to it, in order to submit in JavaScript

everyone I am newbie to JavaScript and Html and i am trying to concatenate the user input in html form and giving an ID and submit, in order to give command to my controller to act accordingly.
This is basically setting up schedule for port 1 and command goes like [NORMAL 122(STARTTIMESTOPTIME DAYSESSION)I haven't included session yet.
function Port1_sch_On_off(){
if(connected_flag==1){
client.subscribe("lazy/test");
message = new Paho.MQTT.Message("NORMAL 122 + document.getElementById('port1_timeday'.value)");
message.destinationName = "lazy/test";
client.send(message);
}
else {
console.log("not connected")
}
return false;
}
<tr height=40>
<td><style="text-align:middle">PORT1_SCH_ON_OFF</td>
<td width=40></td>
<td><form id="port1_timeday" oninput="port1_timeday.value = start_time.valueAsNumber start_day.valueAsNumber stop_time.valueAsNumber stop_day ">
<input name="start_time" id="start_time" type="time" min="00:00" max="24:00" required/>
<span class="hours"></span>
<label for="start_day">Day:</label>
<select name="start_day" id="start_day">
<option value="1">MON</option>
<option value="2">TUES</option>
<option value="3">WED</option>
<option value="4">THRUS</option>
<option value="5">FRI</option>
<option value="6">SAT</option>
<option value="0">SUN</option>
</select>
</label>
<input name="stop_time" id="stop_time" type="time" min="00:00" max="24:00" required/>
<label for="stop_day">Day:</label>
<select name="stop_day" id="stop_day">
<option value="1">MON</option>
<option value="2">TUES</option>
<option value="3">WED</option>
<option value="4">THRUS</option>
<option value="5">FRI</option>
<option value="6">SAT</option>
<option value="0">SUN</option>
</select>
</label>
<output name="port1_timeday" for="start_time start_day stop_time stop_day"></output></td>
<input type="button" onclick="Port1_sch_On_off()" value="Port1_timeday">
</form>
</tr>
</table>
And also I have to add eventlistener for the same with which i haven't started yet.
Here are two main ways to concatenate in javascript :
using the + operator :
message = new Paho.MQTT.Message("NORMAL 122 " + document.getElementById('port1_timeday'.value));
or
using string interpolation :
message = new Paho.MQTT.Message(`NORMAL 122 + ${document.getElementById('port1_timeday'.value)}`);
I hope this answers your question :D
edit 1 :
This function will return your user input cancatenated as such "STARTDAYSTARTTIMESTOPTIMESTOPDAY", you can modify it to return the values in any order :
function cancat_day_time() {
start_time = document.getElementById("start_time").value;
start_day = document.getElementById("start_day").value;
stop_time = document.getElementById("stop_time").value;
stop_day = document.getElementById("stop_day").value;
return `${start_day}${start_time}${stop_day}${stop_time}`;
}
You can then use it in your function Port1_sch_On_off() like this :
function Port1_sch_On_off() {
if (connected_flag == 1) {
client.subscribe("lazy/test");
message = new Paho.MQTT.Message("NORMAL 122 " + cancat_day_time());
message.destinationName = "lazy/test";
client.send(message);
} else {
console.log("not connected")
}
return false;
}
edit 2 :
This is the HTML code that works for me :
<tr height=40>
<td></td>
<td width=40></td>
<td>
<form id="port1_timeday" oninput="">
<input name="start_time" id="start_time" type="time" min="00:00" max="24:00" required/>
<span class="hours"></span>
<label for="start_day">Day:</label>
<select name="start_day" id="start_day">
<option value="1">MON</option>
<option value="2">TUES</option>
<option value="3">WED</option>
<option value="4">THRUS</option>
<option value="5">FRI</option>
<option value="6">SAT</option>
<option value="0">SUN</option>
</select>
</label>
<input name="stop_time" id="stop_time" type="time" min="00:00" max="24:00" required/>
<label for="stop_day">Day:</label>
<select name="stop_day" id="stop_day">
<option value="1">MON</option>
<option value="2">TUES</option>
<option value="3">WED</option>
<option value="4">THRUS</option>
<option value="5">FRI</option>
<option value="6">SAT</option>
<option value="0">SUN</option>
</select>
</label>
</td>
<input type="button" onclick="Port1_sch_On_off()" value="Port1_timeday">
</form>
</tr>

Javascript style.display not working with form

I know there are variations of this question on other threads, but none seem to help me with my answer. Hopefully it is quite a simple one... What am I doing wrong?
I have an option field, and when the user selects "Between" as a drop-down option, I want it to add another input box - in this case called 'AdditionalThreshold'.
function toggleMe(a) {
var e=document.getElementByName("AdditionalThreshold");
if(e.style.display=="none"){
e.style.display = "block";
} else {
e.style.display = "none";
}
return true;
}
<td>
<select name="ThresholdType">
<option value="GreaterThan">Greater than or Equal to</option>
<option value="Between" onClick="toggleMe('BetweenField')">Between</option>
<option value="LessThan">Less than</option>
</select>
</td>
<td>
<input name="Threshold" type="text" size="4" />
<input name="AdditionalThreshold" type="text" id="BetweenField" size="4" style="display:none;">
</td>
I am quite the novice at this so forgive my coding, but any help would be much appreciated.
Thanks
I think you mean to use:
document.getElementsByName("AdditionalThreshold")
in which case returns an array-like structure called a NodeList.
So you would want to do
document.getElementsByName("AdditionalThreshold")[0];
to select the first one. (assuming thats the one you want)
document.getElementById('ThresholdType').addEventListener("change", function(){
var visibility = (this.value === 'Between')?"block":"none";
console.log(this.value);
document.getElementsByName('AdditionalThreshold')[0].style.display = visibility;
})
<select id="ThresholdType">
<option value="GreaterThan">Greater than or Equal to</option>
<option value="Between">Between</option>
<option value="LessThan">Less than</option>
</select>
<input id="Threshold" type="text" size="4" />
<input name="AdditionalThreshold" type="text" id="BetweenField" size="4" style="display:none;">
<select name="ThresholdType">
<option value="GreaterThan">Greater than or Equal to</option>
<option value="Between">Between</option>
<option value="LessThan">Less than</option>
</select>
<input name="Threshold" type="text" size="4" />
<input name="AdditionalThreshold" type="text" id="BetweenField" size="4" class="hide">
<script>
function toggleBetween(event) {
if(event.target.value.toLowerCase() === 'between') {
document.querySelector('#BetweenField').classList.remove('hide');
} else {
document.querySelector('#BetweenField').classList.add('hide');
}
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('select[name="ThresholdType"]').addEventListener('change', toggleBetween, false);
})
</script>
<style>
.hide {
display: none;
}
</style>
http://jsbin.com/pigocekava/1/edit?html,css,js,output

Calculating two persisted bootstrap-select values on .load

Using bootstrap-select -- I am multiplying the values of two select fields in a form, and changing the value of an input field to display the total -- after page load.
How can I have the input field stay empty when just one or neither of the select fields are selected?
Below code only works if both fields are selected.
When neither of the fields are selected, it calculates with the first values of both fields - output becomes $10.
When either one of the fields is selected, it multiplies the selected value with the first value of the non-selected field - output becomes 1 * selected value, or selected value * $10.
PS. Reason I am using .load and not .change is that the fields are persisted with garlic.js
<select class="price selectpicker form-control" id="price" name="price" title="Please choose price.." />
<option>$10</option>
<option>$20</option>
<option>$30</option>
</select>
<select class="multiply selectpicker form-control" id="multiply" name="multiply" title="Please choose multiplier.." />
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" class="form-control" name="total" id="total" readonly="true" />
$(window).on("load", function(){
var price = parseInt($('.price').val());
var multiply = parseInt($('.multiply').val());
var total = price * multiply;
if(total === ''){
$('#total').val('');
} else {
$('#total').val('$' + total);
}
});
The problem was that the 'title' attribute of 'bootstrap-select', does not use a '0' value default option field. So the above code takes the value from the first selectable option when form is loaded.
To go around this issue:
Added the first default option with a zero value in the select tag.
Used the built in 'show.bs.select' to trigger an event when drop-down list is shown, and the built in 'refresh' method to remove it.
Complementary code:
$('.selectpicker').on('show.bs.select', function () {
$('.selectpicker').find('[value=0]').remove();
$('.selectpicker').selectpicker('refresh');
});
<select class="price selectpicker form-control" id="price" name="price" title="Please choose price.." />
<option value="0"></option>
<option value="10">$10</option>
<option value="20">$20</option>
</select>
<select class="multiply selectpicker form-control" id="multiply" name="multiply" title="Please choose multiplier.." />
<option value="0"></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
I hope this will helps you
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script src="http://garlicjs.org/garlic.js"
type="text/javascript"></script>
<form data-persist="garlic" method="POST">
<select class="price selectpicker form-control" id="price" name="price" title="Please choose price.." />
<option value="10">$10</option>
<option value="20">$20</option>
<option value="30">$30</option>
</select>
<select class="multiply selectpicker form-control" id="multiply" name="multiply" title="Please choose multiplier.." />
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name="total" id="total" readonly="true" />
</form>
In script side
<script>
$(window).on("load", function(){
calculate();
$('.selectpicker').on('change',function(){
calculate();
})
});
function calculate()
{
var price = $('.price').val()?parseInt($('.price').val()):10;
var multiply =$('.multiply').val()? parseInt($('.multiply').val()):1;
var total = price * multiply;
if(total === ''){
$('#total').val('');
} else {
$('#total').val('$' + total);
}
}
</script>

Multiple option selects to create unique shopping cart SKU

Is there a way of inserting a string into a field, whereby the string is predetermined depending on what options are selected from two drop down menus?
This is so that a combination of two drop down menus creates a unique SKU for that product, and that string referred to as a SKU is inserted into the input value of the item_number variable and then passed to paypal during checkout.
I will use the example of selling tee-shirts. So the combinations will be black/small, black/large, white/small, & white/large. And each will have a unique SKU of TEESHIRT-BS, TEESHIRT-BL, TEESHIRT-WS & TEESHIRT-WL respectively.
Here is my HTML for the option selects, however, I think I need some JavaScript to insert the SKU into the value field.
<input type="hidden" name="on0" value="colour"><b>select colour</b></><br>
<select name="os0" >
<option value="black">black</option>
<option value="white">white</option>
</select>
<br>
<br>
<input type="hidden" name="on1" value="size"><b>select size</b></><br>
<select name="os1" >
<option value="small">small</option>
<option value="large">large</option>
</select>
<!-- SKU-->
<input type="hidden" name="item_number" value="">
Try the following:
var sizeList = document.getElementById('size');
var colorList = document.getElementById('color');
sizeList.onchange = function() {
generateSku();
};
colorList.onchange = function() {
generateSku();
};
function generateSku() {
var selectedSize = sizeList.options[sizeList.selectedIndex].text;
var selectedColor = colorList.options[colorList.selectedIndex].text;
document.getElementById('sku').value = 'TEESHIRT-' + selectedColor.charAt(0).toUpperCase() + selectedSize.charAt(0).toUpperCase();
}
generateSku();
<input type="hidden" name="on0" value="colour"><b>select colour</b></><br>
<select id="color" name="os0" >
<option value="black">black</option>
<option value="white">white</option>
</select>
<br>
<br>
<input type="hidden" name="on1" value="size"><b>select size</b></><br>
<select id="size" name="os1" >
<option value="small">small</option>
<option value="large">large</option>
</select>
<!-- SKU-->
<input id="sku" name="item_number" value="">

How to pass parameters on onChange of html select

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);
}

Categories