I'm working on a form where I need to compare values of an input. Let's say for example, I have an input which comes from the server with value name1 and then the user changes it to name2. How can I get the initial value and the new value? My script below shows my attempt at resolving this, but when I look at the console output oldAddressNameValue does not have the old value and neither does newAddressNameValue.
What am I doing wrong?
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.data('oldVal', $el.val());
console.log(oldAddressNameValue);
var newAddressNameValue = $el.change(function () {
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
});
console.log(newAddressNameValue);
Thanks
The data function assigns the value to the attribute but will then return the element for jquery chaining.
If you output $el.data('oldVal') directly it should return the value.
console.log($el.data('oldVal'))
or you can assign the result of the single parameter version of .data() to the variable.
The code inside el.change is not executing until the input changes, hence the log is logging nothing, also I'm not so sure about the way you are declaring your variables. This works.
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.val(),
newAddressNameValue;
console.log(oldAddressNameValue);
$el.on('change', function () {
var $this = $(this);
$this.data('newVal', $this.val());
newAddressNameValue = $this.val();
console.log(newAddressNameValue);
});
A working example here
You just placed your console logs at wrong places and the code below shows that your oldVal and newVal are both present.
$(document).ready(function() {
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.data('oldVal', $el.val());
console.log(oldAddressNameValue.data("oldVal"));
var newAddressNameValue = $el.change(function() {
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
console.log(newAddressNameValue.data("newVal"));
console.log(newAddressNameValue.data("oldVal"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inputAddressName" value="123" type="text" />
The data function returns the jQuery wrapped element. If you want to get the actual stored value, you should use $el.data(key) instead.
Here is what you need to do:
var $el = $('#inputAddressName');
$el.data('oldVal', $el.val());
$el.change(function () {
var $this = $(this);
$this.data('newVal', $this.val());
console.log($this.data('oldVal'));
console.log($this.data('newVal'));
});
And here is a fiddle too.
To find the initial value of an <input />, in JavaScript, simply use the defaultValue property:
var input = document.getElementById('inputAddressName'),
oldValue = input.defaultValue,
newValue = input.value;
For example, in jQuery:
$('#inputAddressName').on('change', function () {
var el = this,
oldValue = el.defaultValue,
newValue = el.value;
});
$('#inputAddressName').on('change', function () {
var el = this,
oldValue = el.defaultValue,
newValue = el.value;
console.log(oldValue, newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputAddressName" value="Default value" />
Or, instead, you can use getAttribute('value'), which returns the value from the HTML attribute (which isn't updated as the value changes, only the value property changes):
$('#inputAddressName').on('change', function() {
var el = this,
oldValue = el.getAttribute('value'),
newValue = el.value;
console.log(oldValue, newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputAddressName" value="Default value" />
Try
var $el = $("#inputAddressName");
$el.data({"oldVal":$el.val(), "newVal":void 0});
var oldAddressNameValue = $el.data("oldVal")
, newAddressNameValue;
$el.on("change", function () {
var $this = $(this);
$this.data("newVal", $this.val());
newAddressNameValue = $this.data("newVal");
console.log(oldAddressNameValue, newAddressNameValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="inputAddressName" value="name1" />
Related
I have some fields on my site, and they are the same, but each one of then should update some jquery variable with it's value.
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
I need that depending on the data-atribute, they run the same function, but update the variable pointed in the atribute.
Example:
for = "0";
int = "0";
agi = "0";
$( "input" ).focusout(function() {
data-atribute-of-the-element = $(this).val;
})
I have no know idea how to do this.
And seems stupid to create a different function for every input.
Thanks in advance!
Create an object which has a field which is your variable. Something like below.
var a={'for':'0','int':'0','agi':'0'}
$( "input" ).focusout(function() {
a[$(this).attr('data-atribute')] = $(this).val();
console.log(a.for);
console.log(a.int);
console.log(a.agi);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
.attr() does work, but since you're using data attributes anyway, you may as well use the .data() function designed for them.
See comments in the code snippet for explanation:
/* Set up an object to contain the values you're capturing.
This means we won't have to predefine all the variables or
set them individually; it also means you can use reserved words
like "for", which wouldn't work as variables on their own: */
var capturedValues = {};
$( "input" ).focusout(function() {
// This gets the contents of the "data-atribute" attribute:
var theName = $(this).data("atribute");
// This captures the value of the current input field,
// and puts it in the capturedValues object using theName as the key:
capturedValues[theName] = $(this).val();
// Later on you can reference these as e.g. capturedValues.agi
// Show the results (just for demo):
console.log(capturedValues);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
How about:
var for = "0";
var int = "0";
var agi = "0";
$( "input" ).focusout(function(s) {
switch ($(this).attr('data-attribute')) {
case 'for':
for = $(this).val();
break;
case 'int':
int = $(this).val();
break;
case 'agi':
agi = $(this).val();
break;
}
//OR
var t = $(this).attr('data-attribute');
if (t == 'for') for = $(this).val();
else if (t == 'int') int = $(this).val();
else if (t == 'agi') agi = $(this).val();
})
PS: 'atribute' has 2 t's : attribute
Use the .attr function of jQuery:
$( "input" ).focusout(function() {
let data-atribute-of-the-element = $(this).attr('data-atribute');
})
I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">
I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..
I have the following content in -
var jsonObj = [ {"name" : "Jason"},{"name":"Bourne"},{"name":"Peter"},{"name":"Marks"}];
<!---->
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
function getNames(jsonObj){
var response = JSON.stringify(jsonObj);
for ( var i = 0, len = jsonObj.length; i < len; i++) {
var nameVal = jsonObj[i].name;
response = response.replace(nameVal,replaceTxt(nameVal,i));
}
return response;
}
function replaceTxt(nameVal,cnt){
return "<u id='"+cnt+"' name='names' >"+nameVal+"</u> ";
}
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
and html as below -
<button id="getname">Get Name</button>
<div id="nameData"></div>
Double clicking on names value doesn't generating alerts.
are you sure it is..
<dev id="nameData"></dev>
OR
<div id="nameData"></div>
this works...but you have an extra }); in the question...(don't know if it is a typo)
fiddle here
Try this:
$(document).ready(function(){
$('u[name="names"]').live("dblclick", function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
Try moving this code:
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
inside
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
like:
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
});
You don't need the last "});" Or you didn't paste the whole code.
Look here: http://jsfiddle.net/4cajw/1/
As your code suggest that you are .dblclick()ing on dynamically generated element, that don't work, you have to select parent elem which exist in the document
$(document).on('dblclick','u[name="names"]', function(){
var currentId = $(this).attr('id');
alert(currentId);
});
try this out.
JSON.stringify - object -> JSON.
JSON.parse - JSON -> object
What I want to do is whenever I type a value in the text field, the value typed will be displayed right away.
How do I do it exactly? Is there anyway I could put the value in a variable and use it right away without using onClick?
Here is how I would do it:
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()">
<div id="div1"></div>
I don't think you can do it without any events.
Maybe you can do it with HTML5's <output> tag. I don't know it very well, but try some research.
W3Schools have some good examples.
Hope this can help you
Without using the change event? Why on earth would you want this? The only alternative I can think of would be polling at an interval. Something like:
var theValue = "";
var theTextBox = document.getElementById('myTextBox');
// Run 10 times per second (every 100ms)
setInterval(function() {
// Check if the value has changed
if(theTextBox.value != theValue)
{
theValue = theTextBox.value;
}
}, 100);
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
function changenew(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()" onchange="changenew()">
is it Possible
you can check to see if your input field is in focus, then listen for any key input events and update your display field with the appropriate characters.
html:
<input type="text" id="myText"/>
<span id="output"></span>
js:
var myText = document.getElementById("myText");
myText.onkeyup = function(){
var output = document.getElementById("output");
output.innerHTML = this.value;
}
demo : http://jsfiddle.net/seUBJ/