Keyup function into form element - javascript

I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the <div id="viewer">
This is the script as I have it now :
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
}, 0);
});
$("#viewer").text($('#Website').val().replace(/^\$/, ''));
});
This is the html :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>

if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));

Just use that selector then
$("input[data-cost][data-debt]")

I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />
Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);
I don't believe having an attribute named simply "debt" as you have it above is valid.

I'd do it this way (setTimeout was useless) :
$(function () {
$('#account_balance1').on('keyup blur paste', function () {
var self = this;
var nextCheckbox = $(self).next("input[type='checkbox']");
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
nextCheckbox.data({
cost: str,
debt: str
});
/*
You won't be able to see changes if you inspect element,
so just check in console
*/
console.log(nextCheckbox.data());
});
});
And your html markup must be slightly modified :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value="" />
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />
<!--I added the viewer to check if everything works properly -->
<div id="viewer"></div>

Related

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

Textarea realtime update by multiple input values

This is my form example:
<form action="" method="POST">
<input type="text" name="firstTarget" />
<input type="text" name="secondTarget" />
<input type="text" name="thirdTarget" />
<textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
I want to update my textarea value in realtime by replacing the words firstTarget, secondTarget and thirdTarget with the actual values from firstTarget, secondTarget and thirdTarget inputs.
You can do something like this:
/* cache original value so we keep the keywords*/
var txt=$('textarea').val();
$('input').keyup(function(){
var newText=txt;
newText=newText.replace( this.name, this.value);
$('textarea').val(newText);
});
One issue however is if textarea is not set as readonly and user changes anything within it this won't work as it relies on storing the original value and changing that. Would need to know more about use case for this setup to help advance it further.
Same issue exists in other solutions as well if user touches any of the keywords all will fail
DEMO
Here's a solution that stores the input value on every keyup so textarea can be edited by user as well.
$('input').keyup(function(){
/* value to be replaced is stored in data object*/
var regVal=$(this).data('replace');
var newText=$('textarea').val().replace( regVal, this.value);
/* store value that will get replaced*/
$(this).data('replace', this.value)
$('textarea').val(newText);
}).each(function(){
/* on page load set initial replacement value as name of input*/
$(this).data('replace', this.name);
});
Only limitation is it assumes no duplicate entries by user
DEMO
HTML:
<form action="" method="POST">
<input type="text" name="firstTarget" onblur="tst(this);" />
<input type="text" name="secondTarget" onblur="tst(this);" />
<input type="text" name="thirdTarget" onblur="tst(this);" />
<textarea style="width:500px; height: 100px;" name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
And javascript:
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}
Working jsfiddle demo here
EDIT:
should you want to update multple instances of your needles like firstTarget, then you need to create the regex on the fly so you can pass it the global flag.
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(RegExp(elm.getAttribute('name'), 'g'), elm.value);
}
Working jsfiddle demo here
you can use this code to do it:
$('firstTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('secondTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('thirdTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
enjoy!!!

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

put html input values into javascript object

Why isn't this code giving me an object with the keys as the ids of the text inputs, and the values as the values of the text inputs?
JS
$(document).ready(function () {
$('body').on('click', '#btn', function () {
var address = {};
$('input[type="text"].address').each(function (index, element) {
address[element.id] = $(element).val();
});
console.log(address);
});
});
HTML
<input class="address" id="attn" value="john doe">
<input class="address" id="address_1" value="1234 sample st">
<input class="address" id="address_2" value="Suite 1">
<input class="address" id="city" value="chicago">
<input class="address" id="state" value="IL">
<input class="address" id="zip" value="12345">
<input class="address" id="country" value="US">
<input type="button" id="btn" value="btn" />
jsbin
It's because your inputs don't have type="text" thus $('input[type="text"].address') is not returning anything.
It's better to add them to signify that the inputs are of type text.
Your inputs do not have the [type=text] attribute, so your selector matches none of them. Simply remove it, or use the :text selector:
var address = {};
$(':text.address').each(function (index, element) {
address[element.id] = element.value;
});
console.log(address);
(updated demo)
The jQuery attribute selector (as well as browser query selectors) work with the DOM elements rather than their properties. If you do not explicitly have the type attribute declaration on your the input elements, $("[type]") and document.querySelector("[type]") will not find the element even if its type property is text (http://jsfiddle.net/g76UC/).
The simplest solution is to add type=text to the input elements in your HTML. Another is to use a different selector that does not require this attribute definition. The final (and least desirable) would be to create a separate selector such as :prop that checks the element's type property instead. However this already exists in the form of jQuery's :text.
Use this
$('input.address').each(function () {
address[this.id]= $(this).val();
});
Demo http://jsbin.com/osufok/12/edit
Try out this one http://jsfiddle.net/adiioo7/TPYtg/
$(document).ready(function () {
$('#btn').on('click', function () {
var address = {};
$('.address').each(function (index, element) {
address[element.id] = $(element).val();
});
console.log(address);
});
});

Categories

Resources