Set the default value of an input text - javascript

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

Related

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

Form HTML not getting updated.

Here's something weird
<form>
<input type="text" id="test" value="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert($(this).html());
});
</script>
http://jsfiddle.net/F6XvW/
I change the value of the input field, then click submit to get the HTML, but the value is not updated inside the HTML? What's up with that? How to get the updated HTML?
What the user inputs is never changing the HTML. It's a form value which will be sent as a parameter to the server.
See here: your jsfiddle updated:
<form>
<input type="text" id="test" placeholder="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert('inputted value = ' + $(this).find('input[type=text]').val());
});
</script>
If you really want to update the DOM, you have to manually set it: http://jsfiddle.net/F6XvW/3/
JS
$('form').submit(function(ev){
ev.preventDefault();
$('#test').attr("value", $('#test').val());
alert('changed input value to: ' + $(this).find('input[type=text]').val());
});
Changing the input of a value does not change the Document Object Model (DOM).
SOLUTION
$('form').submit(function(ev) {
ev.preventDefault();
var newinputval = $(this).find('input[type=text]').val();
var newhtml = $(this).html();
newhtml = newhtml.replace("abc", newinputval);
alert(newhtml);
});
As you see I first receive the new input value, then I get the HTML and replace the DOM's value with the current input value. Now it does exactly the thing that you want.
JSFiddle demo
The value attribute shows the default value, not the current value (which is available in the DOM property of the same name.
If you want to get the current value, then you would have to loop over all the form controls and get their values from the DOM.
You are reading out the initial HTML - changing value on the page will not change in this HTML. Try:
$('form').submit(function(ev){
ev.preventDefault();
alert($('#test').val());
});
...to get the value of the input.
If you want to get value of any input use
$('form').submit(function(ev){
ev.preventDefault();
alert($("#test").val());
});
$('input').val();
in forms you can use .serialize();

clear text box using JS function in a href on click

I have this function:
<script>
function ClearTextBox(textbox_name) {
$(textbox_name).val("")
}
</script>
that removes values from a text input
i am trying to call it using:
Clear
but its not clearing the text box
You should use Unobtrusive JavaScript .
Try this code.
$('a').on('click',function(){
$('#customercompany1').val("");
});
It seems working fine for me.. but the console shows the following error
Uncaught SyntaxError: Unexpected token )
this is due to the javascript:void(); in your href attribute.
so i changed the mark up to
Clear
<input type="text" id="customercompany1" value="test value" />
and the script as
function ClearTextBox(textboxname) {
$(textboxname).val(" ");
return false;
}
Hope this helps....
DEMO HERE
Write your function like this:
function ClearTextBox(myInput) {
var txtBox = document.getElementById(myInput);
txtBox.value = "";
return false;
}
And write your html like this:
Clear
<input type="text" id="customercompany1" />
Need to see your HTML to be sure, but I'm guessing your text box looks like this :
<input type="text" name="customercompany1"/>
and it needs to look like this :
<input type="text" name="customercompany1" id="customercompany1"/>
The '#' jQuery selector matches on the id attribute, not the name attribute.
(This is true if you have used a textarea rather than an input)

Keyup function into form element

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>

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!!!

Categories

Resources