$(element).val('newvalue') Is Not Reflected in element.outerHTML - javascript

I am unable to see the value attribute of input elements when using element.outerHTML. Problem is with all input types; example HTML:
<input type="text" id="copy-paste-textarea" />
Example JavaScript:
<script type="text/javascript">
$('#copy-paste-textarea').on('click', function(e) {
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// Output: <input id="copy-paste-textarea" type="text">
$(this).val('hello!');
$(this).addClass('world!');
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// Output: <input id="copy-paste-textarea" class="world!" type="text">
});
</script>
When I run this code above, I see that the change from addClass() is reflected in this.outerHTML, but the change of val() is not. BUT -- I see that the field is indeed actually being populated with the values. I want output to be this:
// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">
The html() function produces the same results. I would like a solution that works on any input type (select, textarea, etc.).
Similar answer here will only work on textareas: Cannot get outerHTML/value of a dynamically added textarea

This is because elements have "properties", which store dynamic information only in memory as expressed by the JavaScript DOM object and they also have "attributes" where the element's actual markup is recorded in memory and is accessible via the HTML parser.
JQuery's .val() method writes data to an in-memory only property.
To get what you want, you must set the value attribute using
JQuery's .attr() method.
The subtle, but important difference between properties and attributes is what contributes to the confusion between JQuery's .prop() and .attr() methods.
$('#copy-paste-textarea').on('click', function(e) {
console.log("input field's outerHTML???" + this.outerHTML + "|");
// You must set the attribute for it to be picked up in the HTML
$(this).attr("value", "hello!");
$(this).addClass('world!');
console.log("input field's outerHTML???" + this.outerHTML + "|");
});
// For a textarea, you need to get the content of the tags with .text()
$('textarea').on('click', function(e) {
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// You must set the attribute for it to be picked up in the HTML
$(this).text("value", "hello!");
$(this).addClass('world');
console.log("Text area's outerHTML???" + this.outerHTML + "|");
});
.world {
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="copy-paste-textarea">
<textarea></textarea>

Related

Jimdo: Add placeholder to html using javascript / jquery

Due to limitations of the webhoster "Jimdo" I can not change html document to insert a "placeholder" into a text field. Is there a way to add that attribute using javascript or jquery?
I have already tried a few codes that I found here but it did not work for me. Maybe I just put a bracket wrong or the code was not compatible with Jimdo's head-area...
This is the code from Jimdo.
<input type="text" name="url" id="url9611056885" value="" class="single">
Screenshot:
Using jQuery .attr():
$("#url9611056885").attr("placeholder","I'm a placeholder");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="url" id="url9611056885" value="" class="single">
You can use .setAttribute to do that.
document.getElementById("url9611056885").setAttribute("placeholder", "Hey! I'm alive!");
<input type="text" name="url" id="url9611056885" value="" class="single">
No need for jQuery, a plain JavaScript solution. A function that accept two arguments the first represent the element itself or a string representing its ID, and the second argument is the placeholder string:
function addPlaceholder(el, ph) {
 if(typeof el === 'string') {
   el = document.getElementById(el);
 } else if(el instanceof HTMLElement === false) {
   console.log('Not a valid HTML element.');
   return false;
}
 el.setAttribute('placeholder', ph);
return true;
}
addPlaceholder('input1', "a placeholder for input 1"); // sending the ID of the input element
addPlaceholder(document.getElementById('input2'), "a placeholder for input 2"); // sending the input element itself
addPlaceholder(window, "will not work!"); // sending a non-valid HTML element here the window object, a log in the console will appear and the function returns false.
<input type="text" id="input1" />
<input type="text" id="input2" />
In javascript use the setAttribute method.
var element= document.getElementById("url9611056885");
element.setAttribute("placeholder", "SOME PLACEHOLDER");
In JQuery use attr method.
$("#url9611056885").attr("placeholder","SOME PLACEHOLDER");
You may traverse in the form searching label having for attribute which will direct to target input and assign the inner text within label as placeholder to input.
$(function() {
$('form').find('label[for]').each(function() {
var lbl = $(this);
var cnt = $('#' + lbl.prop('for'));
if (cnt.is(":text") || cnt.is(":password") || cnt.is("textarea")) {
cnt.prop('placeholder', lbl.text());
}
});
});
P.S. Make sure that you have imported jQuery in your page before above code snippet.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm not into java or jquery and i have no idea what to do right now
You had jQuery tag in your post, hence I given solution based on that tag.

Syntax for Displaying name of a textbox with alert

How can i show the name "First Textbox Name", I have tried a multitude of things but nothing seems to work.
This is the text box among other textboxes.
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text" oninput="calculate()" /></td>
</td>
<script>
var x = document.getElementById("box1").WhatwouldGohere?
alert(x);
</script>
Textboxes don't have a closing tag and therefore cannot have any innerHTML.
But, you can access other aspects of a textbox. Also, don't use inline HTML event attributes (onclick, onmousover, etc.). Even though you see them used everywhere, it's only because a lot of new JavaScript folks pick up bad habits. There are many reasons not to use them.
// Get a reference to the textbox
var tb = document.getElementById("box1");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
// To get the content of the parent element, use the parentElement property
// Then, access the textContent of that element to only get text (and not
// nested child elements). Finally, strip off any leading or trailing
// spaces from that value (if desired) with .trim()
var parentText = this.parentElement.childNodes[0].textContent.trim();
alert("The text that preceeds the textbox is: " + parentText);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text">
</td>
But, your question has asked about the textbox's "label" and it turns out that there is actually a <label> element that you can and should use because it creates a more accessible UI and makes this even easier:
// Get a reference to the textbox and the label
var tb = document.getElementById("box1");
var lbl = document.querySelector("label[for=box1]");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
alert("The text that preceeds the textbox is: " + lbl.textContent);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>
<label for="box1">FirstTextbox Name:</label>
<input id="box1" name="box1" class="nosonly" type="text">
</td>
Well, you do a basic mistake which many people does having no experience with the DOM model. Keep in mind that the code should be executed after the DOM is initialised, so if you want to show the name of the textarea do the following as it's visible that you are using jQuery:
<td>
<label>Label for Box 1</label>
<textarea id="box1"></textarea>
</td>
<script>
$(function() {
alert("My box name is "+ $('#box1').prevAll('label').html());
});
</script>
if no label tag (which is not very clever BTW):
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text" oninput="calculate()" /></td>
</td>
<script>
$(function() {
alert("My box name is "+ $('#box1').parent().text());
});
</script>
Your initial code was showing that you are using jQuery.
This is a simple representation of your html combined with the code above:
alert($('<div>').html('<td>FirstTextbox Name: <input id="box1" name="box1" class="nosonly" type="text" /></td>').find('#box1').parent().text());
alerts FirstTextbox Name:
Try this
<script>
function calculate() {
var x = $('#box1').val();
alert(x);
}
</script>
<script>
function calculate() {
var x = $('#box1').attr('name')
alert(x);
}
</script>
That would alert the name of your textbox.
Or given your edit you could do:
<script>
function calculate() {
var x = document.getElementById("box1").getAttribute('name');
alert(x);
}
</script>

Get Array of Input fields values and append itinto the associated textarea

I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area
.<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>
<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>
and Here is the js code, but it's not working,
var values = [];
$("input[name='formtype[loans][][description]']").each(function() {
values.push($(this).val());
});
alert(values);
Your selector "input[name='formtype[loans][][description]']" won't match any elements, because the [] in the middle will not match to the [0] or [1] (etc.) in the middle of the actual element name attributes.
For the HTML shown you could use the attribute starts with selector [name^=value]:
$('input[name^="formtype[loans]"]').each(function() {
If each textarea will always immediately follow its associated hidden input then within the .each() loop that iterates over the inputs you can say $(this).next() to get the textarea.
If the textareas might be elsewhere in the DOM then you could find them by selecting by the name attribute based on the name of the current input:
$('textarea[name="' + this.name.replace("comment", "description") + '"')
Demonstrated in context:
$('input[name^="formtype[loans]"]').each(function() {
var val = this.value
// add input's value to end of associated textarea's existing value:
$('textarea[name="' + this.name.replace("comment", "description") + '"')
.val(function(i, v) { return v + ' ' + val })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="Hidden value 0" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area A</textarea>
<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="Hidden value 1" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">Text Area B</textarea>
If you want to simply replace the textarea's current value rather than adding to the end of it then you can simplify the above to:
$('input[name^="formtype[loans]"]').each(function() {
$('textarea[name="' + this.name.replace("comment", "description") + '"')
.val(this.value)
})
var values = [],
inputs = $('input[type="hidden"]'),
textareas = $('textarea');
if (inputs.length === textareas.length) {
$.each(inputs, function(i, input) {
var val = ($(input).val()) ? $(input).val(): undefined;
if (val) {
$(textareas).eq(i).empty().val(val);
}
});
}
alert(values);
The working code above assumes a couple of things:
There will always be one textarea per hidden input.
The associated textarea will always be the next sibling after the hidden input.
Even if that is not the case, there are still various ways to resolve this challenge. But I'll break down the different parts of the code:
First, instantiate your variables. Most importantly, cache your selected HTML elements into vars: touching the DOM is expensive and negatively impacts performance (e.g. querying the DOM each time in a loop).
Next, we put a conditional test to ensure there is one textarea for each input. No need to waste time iterating through a loop looking for elements that aren't there.
Finally, iterate through each of the selected inputs confirming each of them have a value. Again, no need manipulating textarea if there is no value to insert. If there is a value in the input, insert it into the textarea that occupies the same position as the input in each of your arrays of elements.

Jquery `.find()` cannot find `document` `input` with value=

I have a button where i append inputs to the HTML DOM.
Later on i have a button to fetch input values if they matches with a keyword.
In this example "a".
HTML
<button class="btn btn-info" id="btnAddInput">Add input</button>
<button class="btn btn-info" id="fetchValue">Fetch value</button>
<div id="inputs"></div>
JS
$('#btnAddInput').on('click', function() {
$('#inputs').append('<input type="text" class="myInput"><br>');
});
$('#fetchValue').on('click', function() {
var value = $(document).find('input[value="a"]');
console.log(value);
});
Fiddle: https://jsfiddle.net/Ljrkdm53/
I´ve learned that, if you add HTML to the DOM with Jquery, you sometimes have to use document as selector, to find elements.
But i have no success in this case.
Inputs that you add is, in my code saved into mysql.
And if you load up all saved inputs at start, the js code find values.
So, what am i missing?
You're confusing the various values associated with inputs. You're not the only one!
The value attribute specifies the initial value of the input. It does not change when the input's value changes, and so since you're appending an input that has no value attribute, then typing in it, it doesn't suddenly get a value attribute — so you can't search for it by that value.
The value property on HTMLInputElement instances reflects the input's current value.
There's also the defaultValue property, which reflects the value attribute.
If you need to find an input based on its current value, there's no CSS selector that will do it, you need to use a broader search and filter:
var inputsWithA = $("input").filter(function() {
return this.value == "a";
});
Here's a quick example showing the values of an input's value property, defaultValue property, and value attribute:
$("button").on("click", function() {
var input = $("input");
msg("The input's <code>value</code> property is: '" + input.val() + "'");
msg("The input's <code>defaultValue</code> property is: '" + input.prop("defaultValue") + "'");
msg("The input's <code>value</code> <strong>attribute</strong> is: '" + input.attr("value") + "'");
msg("We can only use CSS with the attribute, so for instance <code>$('input[value=\"original\"]')</code> will find it but <code>$('input[value=\"" + input.val() + "\"]')</code> will not:");
msg("<code>$('input[value=\"original\"]')</code> found it? " +
($('input[value="original"]').length ? "Yes" : "No")
);
msg("<code>$('input[value=\"" + input.val() + "\"]')</code> found it? " +
($('input[value="' + input.val() + '"]').length ? "Yes" : "No")
);
});
function msg(html) {
$("<p>").html(html).appendTo(document.body);
}
<p>Type something in the input, then click the button:</p>
<input type="text" value="original">
<button type="button">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If I run that and change the input's value to "updated" before clicking the button, I get:
The input's value property is: 'updated'
The input's defaultValue property is: 'original'
The input's value attribute is: 'original'
We can only use CSS with the attribute, so for instance $('input[value="original"]') will find it but $('input[value="updated"]') will not:
$('input[value="original"]') found it? Yes
$('input[value="updated"]') found it? No
Here is the code you need.
$('#btnAddInput').on('click', function() {
$('#inputs').append('<input type="text" class="myInput"><br>');
});
$('#fetchValue').on('click', function() {
var value = $('.myInput').val();
console.log(value);
});
You can check it working here:
jsfiddle.net/Ljrkdm53/7
What you are missing is that the find returns an array of objects and not one value and that the value selector only uses the initial value. You need to use an each function on the value you have now to do something with it.
$(document).find('input').each(function () {
if( $(this).val() == "a")
console.log( $(this).val());
});
Try with each function.
$('input').each(function() {
if ($(this).val() == 'a') {
console.log('a');
}
});

Refactor replace within jquery

Working version http://jsfiddle.net/uxBZN/
Would it be better to just replace password or text within the type (type="password") parameter of html input tag, instead of the whole html input type tag, as seen below?
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$("#security_answer").replaceWith('<input type="text" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="text" name="hnumber" value="'+hnumber+'" id="hnumber">');
} else {
$("#security_answer").replaceWith('<input type="password" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="password" name="hnumber" value="'+hnumber+'" id="hnumber">');
}
});
This needs to work with IE 7/8 and I want to retain the currently entered text.
Yes, you can do that.
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
var type = $(this).is(':checked') ? "text" : "password";
$("#security_answer").replaceWith('<input type="' + type + '" name="answer" value="'+security_answer+'" id="security_answer" />');
$("#hnumber").replaceWith('<input type="' + type + '" name="hnumber" value="'+hnumber+'" id="hnumber" />');
});
Note: Inside the handler you can use this to refer to #unhide_typing and also if you are using jQuery ver 1.7+ then it is preferrable to use on instead of live.
Replacing some properties of HTML elements with jQuery could be tricky on older versions. I recommend you to stay with .prop() function and do not replace DOM elements.
So, your code should be this:
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$('#security_answer').prop('type', 'text');
$('#hnumber').prop('type', 'text');
} else {
$('#security_answer').prop('type', 'password');
$('#hnumber').prop('type', 'password');
}
});​
Yes, it's better to just replace the type for a number of reasons:
Better performance (an element isn't getting removed and then a new one getting created/inserted into the DOM)
Doesn't break the browser's built-in undo mechanism (probably not critical for this use-case, but perhaps it is in others).
Any other event handlers bound to the original input won't get removed
Just make sure you use jQuery's .prop() method rather than .attr():
http://jsfiddle.net/uxBZN/2/

Categories