Textbox:
<input class="qty_txt" input id="1234" type="text" placeholder="Current item QTY">
Javascript:
$(".qty_txt").on("change", function () {
var productID = elem.id;
var qty = elem.value;
alert(productID + qty);
});
How can I use the ID from the textbox, define it as 'productID' and define the value of the texbox as 'qty' to use in the rest of the function?
http://jsfiddle.net/VnYm7/4/
One of the easier things to do would be to pass in the current division as a parameter to the function using the jQuery $(this) selector. This way, the same function works for all the .qty-txt classes.
You can use the .attr() method of jQuery to get the ID of the div, and then call .val() to get the value. You could also use native JS' .value method here.
Important to note: the $(document).ready() wrapper around the jQuery code assures that that code will be called right when the page loads. If it weren't called, the browser wouldn't know to do things if the input box is changed.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!--jQuery Google CDN-->
<script type="text/javascript">
$(document).ready(function() {
$(".qty_txt").on("change", function ($(this)) {
var productID = $(this).attr("id");
var qty = $(this).val();
alert(productID + qty);
});
});
</script>
</head>
<body>
<input class="qty_txt" input id="1234" type="text" placeholder="Current item QTY">
</body>
</html>
var productID = $(this).attr('id');
var qty = $(this).val();
This video better illustrates the use of this and contexts in javascript
If you want to retrieve attributes from the event's target, you can use specify a parameter in the function () you pass to on(), like this:
$(".qty_txt").on("change", function (e) {
var productID = e.target.id;
var qty = e.target.value;
alert(productID + ":" + qty);
});
Take a look at this for details.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
</head>
<body>
<input type="text" class="qty_txt" id="id1" />
<input type="text" class="qty_txt" id="id2" />
<input type="text" class="qty_txt" id="id3" />
<script>
$(".qty_txt").on("change", function () {
var productID = this.id, qty = this.value;
alert(productID + qty);
});
</script>
</body>
</html>
This is example with several input with different ids, you may bind the "change" function to all the ".qty_txt" elements! the productID and productValue you may get by the code above!
Related
how do i check values individually of appended inputs
example i want to get the value of only the second appended input thanks
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput">');
});
</script>
<div class="samplediv">
<input type="text" class="sampleinput">
</div>
<button class="addinput"></button>
</body>
</html>
Add a unique class for each input and use that class to get the value. For the second one, use something like:
$("input.num-2).val();
var num = 1;
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput num-' + num + '">');
num++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="samplediv">
</div>
<button class="addinput">Add input</button>
This is just one way (not the best way) to accomplish what you are asking for.
Here is a working example: https://jsfiddle.net/zzukok0j/
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput">');
var counter = 0;
$('.sampleinput').each(function(poop) {
if(counter===1) {
alert( $(this).val() );
} else {
counter++;
}
});
});
use jquery each function to select each field and do whatever you want...
$('input[type="text"]').each(function(){
//do something
});
The following piece of code will allow you to get the value of each of the appended inputs.
var $inputs = $('.samplediv input');
$inputs.each(function(index) {
value = this.val();
// now you can use value for whatever you need
console.log(value);
});
I hope this helps. Happy coding!
I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>
The following javascript code detects the users country via their IP:
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
document.getElementById("country").value(geoip_country_name());
</script>
<script language="JavaScript">
document.write(geoip_country_name());
</script>
In this second script I'm trying to get the name of the country and pass it to the input text corresponding to the country attribute:
<h:form id="newCustomerForm">
<fieldset>
<legend>Register Form</legend>
<p:outputLabel value="Country :" for="country"/>
<p:inputText id="country"
value="#{customerMB.country}"
title="Country"
required="true"
requiredMessage="The country field is required.">
</fieldset>
</h:form>
Update
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript"> window.onload = function() {
document.getElementById("country").value =geoip_country_name();
};
</script>
<script language="JavaScript">
document.write(geoip_country_name());
</script>
But this is didn't work. Any ideas on how to fix my code?
Your syntax for setting the value is incorrect. value is a property you assign, not a function you call, so it should be:
document.getElementById("country").value = geoip_country_name();
You either need to put this script after the country element, or run it in the window.onload handler:
window.onload = function() {
document.getElementById("country").value = geoip_country_name();
}
FIDDLE
You need to add to text box via paramaters / jquery
var input = $('#yourId');
var text = input.val();
input.val(text.substring(0, 1) + '.' + text.substring(1));
The problem is, you want to load the JavaScript before the 'country' element exists.
You have to put the JavaScript part at the end of the HTML file or execute this part in the document ready event, with jQuery you can use $(document).ready(function...);
I want to pass the value of a input field in two spots. But my code only will pass it once. Is there a way to rewrite this to have it show up again down the code?
//HTML:
<input type="text" name="amount" onchange="passValue(this, 'preview_amount')"/>
//Outputs first value
<span id="preview_amount"></span>
//Outputs Nothing
<span id="preview_amount"></span>
//Javascript:
function passValue(e, target){
document.getElementById(target).innerHTML = e.value;
}
Your ids must be unique. Try this... It might work.
//HTML:
<input type="text" name="amount" onchange="passValue(this, 'preview_amount1', 'preview_amount2');"/>
//Outputs first value
<span id="preview_amount1"></span>
//Outputs Nothing
<span id="preview_amount2"></span>
//Javascript:
function passValue(e){
for(var i = 1; i < arguments.length; ++i){
if (document.getElementById(arguments[i]))
document.getElementById(arguments[i]).innerHTML = e.value;
}
}
With this you can pass any number of ids to passValue function without having to change it.
You cannot have duplicate element id's within a DOM document. ids MUST be unique.
Using jquery, and unique IDs, your problem becomes simple:
<input ... onChange="passValue(this, '#preview_amount1, #preview_amount2');" />
<span id="preview_amount1"></span>
<span id="preview_amount2"></span>
function passValue(e, targets) {
$(targets).innerHTML = e.value;
}
note the different IDs for the two spans, and how those IDs are passed withing the onChange handler.
Also try this one.
<input type="text" id="amount">
<div class="preview_amount"></div>
<div class="preview_amount"></div>
JQUERY
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#id').keypress(function() {
$('.preview_amount').html($(this).val());
});
});
</script>
You can set class name for all the spans you want to update onchange and then set innerHTML according to this class so you won't have to pass different id's to the function.
Fiddle
<input type="text" name="amount" onchange="passValue(this.value)"/>
<span class="set_values_here" id="preview_amount_1"></span>
<span class="set_values_here" id="preview_amount_2"></span>
<script>
function passValue(new_value) {
var els = document.getElementsByClassName("set_values_here");
for(var i=0; i<els.length; i++)
{
document.getElementById(els[i].id).innerHTML = new_value;
}
}
</script>
I'm fairly new to javascript and have a question about how to get a value of an input field without submitting a form. I have the following small piece of code, which I'm using in combination with a realtime-validation script to validate the fields.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var NameValue = document.forms["FormName"]["nameValidation"].value;
</script>
</form>
I want the var NameValue to be the value of what you type into the input field so I can use it in the message which appears after the validation. When I change the value of the input field without submitting the form, the var NameValue is stil set to "HelloWorld". After doing some research I found out I could solve it using jQuery and it's function serialize(). Is there a way to do this without jQuery?
Without jQuery :
var value = document.getElementById('nameValidation').value;
The syntax you had would be usable to get an input by its name, not its id.
If what you want is to use this value when it changes, you can do that :
var nameValidationInput = document.getElementById('nameValidation');
function useValue() {
var NameValue = nameValidationInput.value;
// use it
alert(NameValue); // just to show the new value
}
nameValidationInput.onchange = useValue;
nameValidationInput.onblur = useValue;
Your code works. It assign value of your input field to var NameValue. What you explained and what JQuery serialize does are two different things.
Everything you need is to assign your code to right event:
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" onchange="myFunction()"/>
</form>
<script type="text/javascript">
function myFunction(){
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
​see the JSFiddle.
use the onchange or onblur event to call this code:
var NameValue = document.forms["FormName"]["nameValidation"].value;
This way it will get activated when the cursor leaves the textbox
<input type="text" id="nameValidation" value="HelloWorld" onblur="changeVal();" />
<script type="text/javascript">
function changeVal() {
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
In your example, the variable only gets the value assigned to it at that moment in time. It does not update when the textbox updates. You need to trigger a function [onchange or onblur or keypress] and reset the variable to the new value.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var myTextbox = document.getElementById("nameValidation");
var nameValue = myTextbox.value;
myTextbox.onchange = function() {
nameValue = myTextbox.value;
};
</script>
</form>
You can let your client-side code respond to a change in the value of the textbox, like so:
$(document).ready(function(){
$("#nameValidation").on('change', function() {
var value = $("#nameValidation").value;
//do your work here
}
})