Change label text using JQuery - javascript

I want the labels to change whenever the user changes from Metric to Imperial.
It correctly detects the change and stores the current value selected, steps into the if statement, but then nothing happens.
Here is my JavaScript.
$(document).ready(function()
{
$("select[name = unit]").change(function()
{
var selected = $("option:selected", this).text();
if(selected == "Metric (cm)")
{
$("label[for = unit]").text("mm");
}
else if(selected == "Imperial (inches)")
{
$("label[for = unit]").text("in");
}
});
})
And my html.
<form name ="Calculator">
Unit of Measurement:
<select name = "unit">
<option value = "120904000">
Metric (cm)
</option>
<option value = "4760000">
Imperial (inches)
</option>
</select>
<br>
Root Diameter: <input type = "text" name = "root" autocomplete = "off">
<label for = "unit"></label>
<br>
Width between bearings: <input type = "text" name = "bearings" autocomplete = "off">
<label for = "unit"></label>
<br>
End Fixity:
<select name = "fixity">
<option value = ".36">
1
</option>
<option value = "1.0">
2
</option>
<option value = "1.47">
3
</option>
<option value = "2.23">
4
</option>
</select>
<br>
Max Speed (RPM): <input type = "text" name = "speed" autocomplete = "off"><br>
Reset
Calculate
Exit
</form>

I cant really guess where u missing.But check this js fiddle where i used your code and its working absolutely fine for me .
Your code Fiddle
$("select[name = unit]").change(function()
{
var selected = $("option:selected", this).text().trim();
if(selected == "Metric (cm)")
{
$("label[for = unit]").text("mm");
}
else if(selected == "Imperial (inches)")
{
$("label[for = unit]").text("inches");
} });
I updated the jsfiddle for you .You needed to add this trim at the end like this :
var selected = $("option:selected", this).text().trim();
and you set to go.
Here is updated jsfiddle :
updated code fiddle

Related

Change hidden input field value according to select options

I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)

Calculate the weight of planet on drop downs and print it to input type

I have the code for a form with some drop down menus with different options in it and I have also create alert pop up message so that they cannot select same planet now. I also have disable one input on one textbox for input because I only can put one input.
My question is how do I calculate the weight of the planet based on the dropdown box I selected? And also print/ display it on the input type means if I select earth and my input type (weight) is 60N, if my second select is Venus it will calculate the weight for me and print / display it to input type.
Below is roughly my HTML code and JavaScript code. I'm new to JavaScript.
html :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name="123" id="text1"
onchange="process_selection(this)" placeholder=""> N
</select>
<br>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name = "123" id="text2"
onchange="process_selection(this)" placeholder=""> N
</select>
javascript :
<script type="text/javascript">
function process_selection(obj)
{
var input1 = document.getElementById("select1").value;
var input2 = document.getElementById("select2").value;
var texta = document.getElementById("text1");
var textb = document.getElementById("text2");
if(input1 == input2)
{
alert("Please select other planet");
}
if(texta.value != "")
{
document.getElementById("text2").disabled = true ;
}
if(textb.value != "")
{
document.getElementById("text1").disabled = true ;
}
// var xx = input1.options[input1.selectedIndex].value;
var SurfaceGravityEarth = 1;
var SurfaceGravityVenus= 0.907;
var SurfaceGravityMars= 0.377;
var SurfaceGravityJupiter= 2.364;
var weight1 , weight2;
// var sg1;
// var sg2;
if (input1 == "0" )
{
weight1 = document.getElementById("text1") * SurfaceGravityEarth;
}
if (input2 == "1" )
{
weight2 = document.getElementById("text1") * SurfaceGravityVenus ;
document.getElementById("text2").value= weight2 ;
}
}
I'm stuck at the calculation part.
first, get the value of textbox and convert it to number type (integer, float etc).
Try the following code:
weight1 = parseInt(document.getElementById("text1").value) * SurfaceGravityEarth;
use parseInt() to convert to integer type.
if you want to convert to float type use parseFloat()
or you can simply use Number() method for both integer and floating point numbers

Using jquery data attributes with each function

I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.
I'm using an each function to loop through all the products they add to sum the price.
For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!
HTML
<select class="form-control onChangePrice system1" name="SystemModel">
<option value="">Select...</option>
<option value="3300" data-min-price="3000">System 1</option>
<option value="4500" data-min-price="4000">System 2</option>
<option value="6000" data-min-price="5500">System 3</option>
<option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>
JS
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("minPrice");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!
Thanks
You're doing a couple of things slightly wrong here:
$('.system1').each(function(){
should be:
$('.system1 option').each(function(){
and
systemEachMin = $(this).data("minPrice");
should be:
systemEachMin = $(this).data("min-price");
So in full:
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1 option').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("min-price");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.
this.options will return all the options in an array
or you could use the following for the selected options data attribute
$(this).find('option:selected').data("minPrice")
or
$("option:selected", this).data("minPrice")

How to compare <option> “data-names” in an “if” statement?

I have a slight issue. I have options with a “value” and a “data-name”.
<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>
I want the computer return a specific value if the selected option is a certain “data-name”
Say there are 2 “data-names”, X and Y.
How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?
I’m thinking something along the lines of this:
var data_name1 = e.options[e.selectedIndex].dataset.name1;
if (data_name1 == “X”) {
…
}
else if (data_name == “Y”) {
…
}
else {
…
}
Is this possible?
Thanks!
Full code---
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
You need to use the == operator to compare objects.
= is an assignment expression.
if (data_name1 == “X”) {
// Operations if data_name is equal to X
}
else if (data_name == “Y”) {
// Operations is data_name is equal to Y
}
else {
}

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