Inner HTML with input values - javascript

have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):
http://jsfiddle.net/F7urT/2/
jQuery:
jQuery(document).ready(function($) {
$('.send').click(function() {
alert( $('.content').html() );
return false;
});
});​
html:
<div class="content">
<input type="text" name="input" value="Old Value" />
<input type="button" class="send" value="Send" />
</div>​
If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?

The new value is stored as a property not an attribute, the value can be obtained by inputelement.value, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.
For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option
http://jsfiddle.net/mowglisanu/F7urT/5/

this solution is better. works for more inputs.
$('input[type=text]').attr('value', function (i, val) { return val; });
$('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
$('textarea').html(function () { return this.value; });
$('select').find(':selected').attr('selected', 'selected');

You can't get it with .innerHTML (.html()). Writing into an element doesn't modify the html markup, nor will it change the value attribute in actual markup.
You can only access the current content by directly asking the element for its .value - value. Using jQuery, you can do that via .val() too.

$('#input_id').attr('value',$('#input_id').val()); will put the value into the html

DanCZ & Musa solutions works pretty good, but I had trouble with the textarea.
I have to implement this in a Typescript project and the only way I've found to make the textarea show the value is this :
textarea.innerHTML = textarea.value;

Related

How to update a field on .focusout()?

I would like, upon loosing focus on an <input> field, to perform a few operations on the value of this field, including changing the content itself (so that it is uppercase)
In the following code:
HTML
<input id="name" type="text"></input>
<div id="upper"></div>
JavaScript + jQuery
$("#name")
.focusout(function() {
// get the text from the form which lost focus
name = $("#name").val();
// turn it into uppercase
name = name.toUpperCase();
// update the form and another entry
$("#upper").text(name);
$("#name").text(name);
})
the event is correctly caught and the <div> is updated with the lowercase text. The content of the field, however, is not updated.
Is it possible to update the content of an <input> field upon leaving it?
Change text() to val() for field
$("#name").val(name);
Use jQuery.val() to set the Value, not jQuery.text(), also note this in handler-function refers to Element on which event is invoked hence this could be used instead of specified-selector
You could try this simplified code:
$("#name").focusout(function() {
var name = this.value.toUpperCase();
$("#upper").text(name);
$(this).val(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="name" type="text"></input>
<div id="upper"></div>

jQuery, detecting actual input text value

I'm running into an issue where the value grabbed by jQuery, and what's actually in the input text field, are different.
A form with a variety of inputs are populated when the page loads with information from our database. Thus, the input text fields all have a value.
When the form is submitted, I have a function that runs first to check for text inputs. This is a portion of that function:
$("form#accountSettingsForm input").each(function(){
var input = $(this);
var value = input.attr("value");
}
Lets say the input value is 12 when the page had initially loaded. If I delete the 12 in the textbox and leave the field blank, and submit the form, the above code retrieved "value" is still 12, not empty.
How can I detect what's actually the textbox's value? Thanks in advance.
This is a situation where there's a difference between the value attribute and the value property. The attribute comes from the HTML, the property is from the dynamic state of the DOM. To get the current value of an input after the user has modified it, use the jQuery .val() method.
$("#accountSettingsForm").submit(function() {
$(this).find("input").each(function() {
var input = $(this);
var value = input.val();
console.log(this.name + " = " + value);
});
return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="accountSettingsForm">
Input 1:
<input name="field1" type="text">
<br>Input 2:
<input name="field2" type="text">
<br>
<input name="submit" type="submit">
</form>
The following appears to work well. If you want to regularly remember/store the value, register for the on('input') event. With this, you get an event every time the user types in the textbox:
$("#accountSettingsForm :input").on('input', function() {
console.log($(this).val());
});
As far as I can tell, the $(this).val() method of access works fine.
Here's a JSFiddle: https://jsfiddle.net/uz8k7rjp/
And the original post where I got this method: JQuery: detect change in input field

How to get websites actual HTML code by JS?

I have a website with a form. The form is filled by user with data for example i show to user:
<input type='text' value="" name="dsa" />
And he fills it with value of "3";
And he clicks button "save". Now i want to have the whole HTML of the website including values of fields. So i use:
document.documentElement.innerHTML
But i get:
<input type='text' value="" name="dsa" />
But i want to get this:
<input type='text' value="3" name="dsa" />
NOTICE I want to take the whole HTML of the website, not only one field. I dont know what fields will be on the website so i need a general solution.
AFAIK you can't get this from the HTML code, as the HTML code does not change when the user inputs something in a Input text field.
What you could do is get all input fields on the page and get their values with something like this:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
The code is from this post: https://stackoverflow.com/a/2214077/312312
I was too lazy to write it down my self :P
In jQuery I do
$(function() {
$('input').keyup(function() {
$(this).attr('value', $(this).val());
});
});​
Because the value attribute isn't set after key up
You could try to set a live event on a whole document that will set attribustes to html with values user set in or set them on your submit.
First way for example
$("body").on("change", "select,input,textarea", function(){
$(this).attr("value", $(this).val());
});
But this should not be done so blindly, and you'll get problems with reset. And you should solve problem with selected radio, checkbox and other attributes, not only values.
Second way is to serialize whole page when it really needed.
var serialize = function(el){
$("select, input, textarea").each(function(){
$(this).attr("value", $(this).val()); //the same way as upper
});
}
$(".serialize").click(function(){
var inner = $("body"),
html;
serialize(inner);
html = inner.html(); //here you will get whole html with setted attributes
});
This way seems to be better because there wont be delegation of unnecessary event.
http://jsfiddle.net/CeAXL/2/ - test example.
But in both ways it's not good idea to set permanent values to DOM itself.

Inserting JQUERY value into hidden field of html

Hi I want to insert a cookie value which I am getting by using jQuery.
I want to grab the value of the cookie and insert it into the html value attribute.
<input id="visitorcookie" type="hidden" value="<script>$.cookie('visitorCookie');</script>" name="com.silverpop.iMAWebCookie">
Is this correct how I am doing it?
Not at all actually. The value attitribute won't execute any code, it just can store a value.
Do this: when the DOM is ready, select the hidden field by ID with $('#visitorcookie') and set it's value with .val():
$(document).ready(function() {
$('#visitorcookie').val($.cookie('visitorCookie'));
});
More about:
jquery selectors
.val() method
$("#visitorcookie").val($.cookie('visitorCookie'));
$('#visitorcookie').val($.cookie('visitorCookie'));

javascript/jquery- parsing through all elements of a radio/check box- how to get text value of each element

I am trying to parse through a checkbox/radio button.
As an example let us consider the html code for a radio button below--
<br/><br/>Lunch-
<input type="radio" name="lunch" value="pasta1" /> Pasta
<input type="radio" name="lunch" value="rissotto1" /> Rissotto
<br/>
Now I am using the following code to obtain both the text value shown on screen (eg "Pasta") as well as the value assigned (eg "pasta1")--
$(jQuery('input[type="radio"], input[type="checkbox"] ', $(element).parent('form'))).each(function()
{
alert(" Text values =" + $(this).text());
alert(" actual values =" + $(this).val());
---SOME MORE CODE---
}
As output, I am not getting any value when I use $(this).text(), although $(this).val() works fine.
How do I get the text values for each element of a radio button/check box... Something that I can use in place of the $(this).text() used above? Is there some other way to obtain the text value (eg "Pasta" or "Risotto" for the example above)?
I don't think you can retrieve the text value with the HTML you have. Ideally you should create label elements to hold the text. e.g.
<input type="radio" name="lunch" value="pasta1" /> <label>Pasta</label>
<input type="radio" name="lunch" value="rissotto1" /> <label>Rissotto</label>
Then you can get the text:
$(this).next().text();
EDIT:
If you can't change the HTML, here is a dirty workaround.
Assuming you have a wrapper element (form or div) of id wrapper around these radio buttons and each radio button has unique value-
/*
* Create mapping between radio button values and texts
*/
var mapping = new Array();
var current_key = '';
$('#wrapper').contents().each(function()
{
if(current_key)
{
mapping[current_key] = $(this).text();
current_key = '';
}
if($(this).attr('type') == 'radio')
{
current_key = $(this).val()
}
});
Then you can easily use the mapping:
$('input[type=radio]').each(function()
{
text = mapping[$(this).val()];
})
.text() is not applicable for those elements who don't have close tag. e.g. <INPUT> <IMG> If you read the documentation of .text() it is clearly written that The .text() method cannot be used on form inputs or scripts.
I'm not sure what you exactly wanted to be shown but giving value attribute will show a text next to Radio Button. Thats how it works. I'm not sure why you want another extra text after that. But if thats the case then solution suggested by #Vikk is right.

Categories

Resources