Persisting textbox value using jQuery - javascript

I'd like to save the newly entered values, so I could reuse them. However, when I try to do the following, it does not work:
// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val());
When the line executes, no errors are generated, yet Firebug doesn't show that the value attribute of el has changed. I tried the following as well, but no luck:
$(el).val($(el).val());
The reason I'm trying to do this is to preserve the values in the text boxes when I append new content to a container using jTemplates. The old content is saved in a variable and then prepended to the container. However, all the values that were entered into the text boxes get lost
var des_cntr = $("#pnlDesignations");
old = des_cntr.html();
des_cntr.setTemplate( $("#tplDesignations").html() );
des_cntr.processTemplate({
Code: code,
Value: val,
DivisionCode: div,
Amount: 0.00
});
des_cntr.prepend(old);
This is the template:
<div id="pnlDesignations">
<script type="text/html" id="tplDesignations">
<div>
<label>{$T.Value} $</label>
<input type="text" value="{$T.Amount}" />
<button>Remove</button>
<input type="hidden" name="code" value="{$T.Code}" />
<input type="hidden" name="div" value="{$T.DivisionCode}" />
</div>
</script>
</div>

You want to save the previous value and use in the next change event?
This example uses .data to save the previous value. See on jsFiddle.
$("input").change(function(){
var $this = $(this);
var prev = $this.data("prev"); // first time is undefined
alert("Prev: " + prev + "\nNow: " + $this.val());
$this.data("prev", $this.val()); // save current value
});
jQuery .data

If you want old/Initial text box value, you can use single line code as follows.
var current_amount_initial_value = $("#form_id").find("input[type='text']id*='current_amount']").prop("defaultValue");
If you want current value in the text box, you can use following code
$("#form_id").find("input[type='text']id*='current_amount']").val();

Related

Jquery Autocomplete not working correctly

I'm using jquery autocomplete.In my case I have multiple autocomplete textbox and hidden field on my page.
e.g
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
and so on...
so when I fire change event on hidden field then it is raised multiple time
below is my code:
$(".myclass").each(function() {
var $empName= $(this);
var $empNumber = $empName.next('input:hidden');
//things to do
//Setting variable e.g url...
$empName.autocomplete(url,{
//code...
}).result(function(event,data,formatted)
{
$empNumber.val(formatted).change();
});
});
In above code $empNumber holds the hidden field which is used to store autocomplete value i.e in this case when
we select any text from autocomplete then that selected employees number will get store in hidden field.
Based on this hidden field value I want to do ajax call which will return full details of the employee based on his
employee number.
So I have written hanldler to change event of the hidden field as below.
$(.emp_num_hidden).on('change',function (
)};
here 'emp_num_hidden' is the class of the hidden field.
Please suggest how can I prevent multiple event on hidden field change.
This is done using the $(this) object. Since the change event has a target, it will only be effecting one element. The callback function is being executed on this element, this. For example:
$(".emp_num_hidden").on('change', function (e){
alert($(this).val());
});
What will happen is that an alert window will be shown when the hidden field is changed, containing the employee number from only that hidden field. You will also notices there are a few fixes to your code.
Personally, I would make use of both id and class attributes on your objects. This gives you wide scope and narrow scope to your selectors.
Example:
HTML
<input class='myclass' type='text' id='entry-txt-1' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-1' />
<input class='myclass' type='text' id='entry-txt-2' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-2' />
jQuery
$(function(){
var $empName, $empNumber;
$(".myclass").each(function(key, el) {
$empName= $(el);
$empNumber = $empName.next("input[type='hidden']");
// things to do
// Setting variable e.g url...
$empName.autocomplete(url, {
//code...
}).result(function(e, d, f){
$empNumber.val(f).change();
});
});
$(".emp_num_hidden").on('change', function(e){
var empId = $(this).attr("id");
var $employeeNumberField = $("#" + empId);
// Do the needful...
});
});
Taking this a bit further, you may want to consider making use of data attributes. You may also want to look at select event for Autocomplete. Something like:
$(function(){
$(".myclass").autocomplete({
source: url,
select: function(e, ui){
$(this).val(ui.item.label);
$(this).data("emp-number", ui.item.value);
$.post("employeedata.php", { n: ui.item.value }, function(data){
$("#empData").html(data);
});
return false;
}
});
});
This assumes that url returns an array objects with label and value properties. This would add the Employee Number as a data-emp-number attribute to the field that the user was making a selection from. The label being their Employee Name, and the value being their Employee Number. You could also use this callback to show all the other employee data based on Employee Number.
A working example: https://jsfiddle.net/Twisty/zmevd0r0/

jquery dynamically print out value of input

I'm working on a dynamic calculation program to practice jquery, but so far it's not going well, I can store the values in a variable, of course (see code here).
<form>
Tafeltje van:
<input type="number" name="tafel" id="tafel" />
Aantal:
<input type="number" name="aantal" id="aantal" />
</form>
<div id="output"></div>
and the JS:
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
How would one be able to print out these values in output while the user is typing in the text fields?
You can bind your code with keyup or input event of the inputs. Then, once you have got the values, you can use either text() or html() to display the values in #output div in whatever format you want.
// $("input").on("keyup", function(){
$("input").on("input", function(){
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
$("#output").text("tafel: " + tafel + " aantal: "+aantal);
});//keyup

Grab the value of latest textbox on a particular variable having multiple textbox with same ID

I want the value of last textbox to be grabbed by the varialble on multiple textbox with same ID.
HTML
<input type="text" id="get"><br>
<input type="text" id="get"><br>
<button id="grab">Click</button><br>
SCRIPT
$("#grab").click(function(){
var value = $("#get").val();
});
Or, a way to delete the first textbox might also work. Working Example
Your HTML is invalid: HTML elements can't have the same id attribute.
Use the class attribute, instead.
You can then use .last() to get the last element that matches the .get selector:
$("#grab").click(function(){
var value = $(".get").last().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="get" value="foo"><br>
<input type="text" class="get" value="bar"><br>
<button id="grab">Click</button><br>
(I added the value attributes for demonstrative purposes. Obviously, they can be removed.)
If you want to get the first element's value if the second one is empty, you could do this:
$("#grab").click(function(){
var firstValue = $(".get").val(); // `.val()` gets the first element's value by default
var secondValue = $(".get").last().val();
var result = secondValue || firstValue;
alert(result);
});
If you don't have any control on ids you should use following solution. If you can change the ids you should change them.
You approach will not work because the id is not unique. It will always get the first input.
$("#grab").click(function() {
// var value = $(this).prev("input").val(); // Will work when there is no `<br>`
alert($('input[id="get"]').last().val());
});
Here $('input[id="get"]') will get all the elements having id get and last() will get the last element from it.
Demo: https://jsfiddle.net/orghoLzg/1/

How do I retrieve data from a textbox using JavaScript?

Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;

Editing html input element from javascript bugs out

I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/

Categories