Okay. So I have this code
<input id="suspect" value="" type="text">
<input id="reason" value="" type="text">
<textarea></textarea>
var suspect = $('input#suspect').text();
var reason = $('input#reason').text();
$('textarea').val('' + suspect + ' and ' + reason + '')
Then I put something in both of those 2 inputs and then the textarea recieves no value from the inputs. How to fix that problem ?
Because when you set the variables there's no text inside the elements from which you're trying to recover the entered-text (incidentally, for inputs you're looking for .val()). If you bind to the focus event:
$('textarea').focus(
function(){
var suspect = $('#suspect').val(),
reason = $('#reason').val();
$(this).val('' + suspect + ' and ' + reason + '');
});
JS Fiddle demo.
Also, in this case (since you've placed the JavaScript after the elements in the DOM, albeit you've omitted the <script></script> tags) you might be okay not using the $(document).ready() event handler, but I'd normally suggest wrapping jQuery in such, just to be sure that events are being bound after the elements to which they're being bound exist in the DOM.
References:
focus().
val().
.text() -- Gets the text inside the elements
.val() -- Gets the value of the elements
Since the text is stored inside the value, therefore you should use .val() instead of .text().
var suspect = $('input#suspect').val(),
reason = $('input#reason').val();
$("textarea").val(suspect+" and "+reason);
If you want instant change try the keyboard events
$(window).keyup(function() {
var suspect = $('input#suspect').val();
var reason = $('input#reason').val();
$('textarea').val('' + suspect + ' and ' + reason + '');
});
see here: http://jsfiddle.net/TtAVS/
You probably want to use val() here instead of text(), and there also needs to be some kind of event (like a click) that causes the data to be extracted from the inputs and put into the textarea.
It also might be worth noting that since id's are unique,
var suspect = $('#suspect').val();
var reason = $('#reason').val();
are sufficient as selectors and (I find) easier to read.
should use .val() to get value from the input box
Related
I have input element and string variable called link. And when i try to add this string like a value inside input element.
I tried to do it by :
$("#inputURL").value(**link**)
$("#inputURL").attr('value',**link**)
and also defined at start:
var inputRow = $('<input type="url" id="inputURL" class="input-url-link"value="' + **link** + '">');
But it doesn't show. I have empty input element but when I inspect element, it have value which equal link. And this all running inside of function.
var inputRow = $('<input type="url" id="inputURL" class="input-url-link">');
P.S. when i try do write 1) and 2) code inside of INSPECT in console - it works. But when i wrote the same inside of code - doesnt work
Use val() function so your JQuery will look like this:
$("#inputURL").val(**link**);
If it doesnt work, try:
$("#inputURL").text(**link**);
Reference here
Like #Learner said in his answer, it's $('#id).val() not value().
And I did some simple code to replicate your situation, it works fine.
I'm guessing you should have wrapped your jQuery code in jQuery(function($){})
See here https://jsfiddle.net/calmdown/74wurk50/4/
I have a fairly complex situation (to me at least):
I have a click function that was used to show an overlay. Inside the click function, the element in question is determined dynamically:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = '#project-details-overlay-' + id;
Now what I'd like to do is something like:
$(el_id).detach();
But I am seeing that this doesn't work because I am passing in an element not a selector. So how would one do this?
What I need to do is grab that element and re-attach it somewhere else. I have tried to just deal with the element's contents using .html() and so forth but because the content, at times contains javascript elements such as slideshows, this doesn't seem to work out too well...
Any suggestions?
should work this way:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
el_id.detach();
});
i'm not familiar with detach.. if you're trying to move it somewhere else:
<div id="somewhereElse"></div>
then you would write:
el_id.appendTo('#somewhereElse');
if you want to keep it where it is AND copy it somewhere else:
el_id.clone().appendTo('#somewhereElse');
lastly, if you're not using el_id anywhere else beyond this one line of code, you don't even need the extra variable... just condense the var statement and the append statement into one:
$('#project-details-overlay-' + id).appendTo('#somewhereElse');
Thanks #erikruina - appendTo() works much better. I ended up fixing it with
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
$(el_id).appendTo('#selected-project');
});
I suspect that the issue is that with detach(); you also need to deal with all the child elements, whereas appendTo() just works.
Yes I have see the post here
And I tried that but the problem is, my jquery object looks more like this:
var $foo = $('<ul><li id="' + line.id + '" label="' + label + '" rel="file">' + line.title + '</li></ul>');
$foo.click(function() { openLink(line.url) });
$foo.appendTo($myDiv);
When $myDiv is fully populated I can do this:
var html = $('<div>').append($('#foo').clone()).remove().html();
And I will see all of the lovely HTML, but I don't know if the click stuff will be preserved. See, I want to save the entire DOM modification to localStorage so I can retrieve it quickly since it's pretty static. I need to be able to store it and all its attributes, then yank it back out and restore it, clicks and all.
Does that make sense?
The only way to do this would be to use inline event handlers, which is a bad (and slow) idea.
Instead, you can convert all of your event handlers to live handlers; they will then automatically apply to all matching elements without having to rebind them after changing the DOM.
Can I completely rely upon jQuery's html() method behaving identical to innerHTML? Is there any difference between innerHTML and jQuery's html() method? If these methods both do the same, can I use jQuery's html() method in place of innerHTML?
My problem is: I am working on already designed pages, the pages contains tables and in JavaScript the innerHTML property is being used to populate them dynamically.
The application is working fine on Firefox but Internet Explorer fires an error: unknown runtime exception. I used jQuery's html() method and IE's error has disappeared. But I'm not sure it will work for all browsers and I'm not sure whether to replace all innerHTML properties with jQuery's html() method.
Thanks a lot.
To answer your question:
.html() will just call .innerHTML after doing some checks for nodeTypes and stuff. It also uses a try/catch block where it tries to use innerHTML first and if that fails, it'll fallback gracefully to jQuery's .empty() + append()
Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!
Run this in internet explorer 7 or 8 and you'll see.
jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!
There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function() {
// the following two blocks of HTML are identical except the P tag is outside the form in the first case
var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";
// <FORM> tag nested within <P>
RunTest("<FORM> tag nested within <P> tag", html1); // succeeds in Internet Explorer
RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1); // fails with added new line in Internet Explorer
// <P> tag nested within <HTML>
RunTest("<P> tag nested within <FORM> tag", html2); // succeeds in Internet Explorer
RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2); // succeeds in Internet Explorer even with \n
});
function RunTest(testName, html) {
// run with jQuery
$("#placeholder").html(html);
var jqueryDOM = $('#placeholder').html();
var jqueryFormSerialize = $("#placeholder form").serialize();
// run with innerHTML
$("#placeholder")[0].innerHTML = html;
var innerHTMLDOM = $('#placeholder').html();
var innerHTMLFormSerialize = $("#placeholder form").serialize();
var expectedSerializedValue = "field1=111&field2=222";
alert( 'TEST NAME: ' + testName + '\n\n' +
'The HTML :\n"' + html + '"\n\n' +
'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +
'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +
'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +
'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED")
);
}
</script>
</head>
<div id="placeholder">
This is #placeholder text will
</div>
</html>
If you're wondering about functionality, then jQuery's .html() performs the same intended functionality as .innerHTML, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html() instead of .innerHTML where possible.
innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.
Given the general support of .innerHTML these days, the only effective difference now is that .html() will execute code in any <script> tags if there are any in the html you give it. .innerHTML, under HTML5, will not.
From the jQuery docs:
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Note: both .innerHTML and .html() can execute js other ways (e.g the onerror attribute).
"This method uses the browser's innerHTML property." - jQuery API
http://api.jquery.com/html/
Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)
if (/(msie|trident)/i.test(navigator.userAgent)) {
var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
Object.defineProperty(HTMLElement.prototype, "innerHTML", {
get: function () {return innerhtml_get.call (this)},
set: function(new_html) {
var childNodes = this.childNodes
for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
this.removeChild (childNodes[0])
}
innerhtml_set.call (this, new_html)
}
})
}
var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)
document.body.innerHTML = ""
console.log (mydiv.innerHTML)
http://jsfiddle.net/DLLbc/9/
The idea: I'm setting the value of an input with type="hidden" via regular Javascript or jQuery.
The issue: neither jQuery nor document.getElementById will find the hidden input, even though I'm absolutely sure the selector is correct and there are no conflicting elements.
The code:
I can't really post much of it, because it's full of rather complicated PHP that confuses me when I just look at it.
Here's the javascript:
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
Note: there's nothing wrong with the selector, and the "input" is a different element that I'm using to reference the hidden.
Here's the HTML:
<input type="hidden" name="s<?=$step_counter?>_budget_hidden"
id="s<?=$step_counter?>_budget_hidden" value="0" />
The code is kind of out of context, but it's more of a general problem with Javascript than a syntactical error. Thoughts?
In $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total); you take two chars before the first underscore in your hidden id. However your hidden id have only one char 's'
EDIT
Ok the <?= ?> was hidden before the question edit.
Do you call your script after the body onload event?
EX:
$(document).ready(function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").bind("keyPressed",function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
}
});
FYI: We can get the hidden input value using jQuery, even we can also edit any hidden input value using jQuery.
I think your way of getting the hidden value using 'substr' method is causing some problem. You are using like substr(0, 2) so are sure that the variable $step_variable is a single digit number, otherwise your code will not return correct result.
I am giving some sample code below, check it once.
Here's the javascript:
var input_id = $("hidden_val").attr("id").substr(1);
$("#" + input_id + "_budget_hidden").val(budg_total);
Here's the HTML:
input type="hidden" class="hidden_val" name="s_budget_hidden" id="s" value="0"
I think this will help you. Let me know if you are not following this flow to solve your issue.
I think that input.id.substr(0,2) says to start at the start of the string, take 2 characters and use that.
http://www.w3schools.com/jsref/jsref_substr.asp
Try using Firebug to see what the result of that method call is.