How to get the text written in text input - javascript

I'm trying to grab the txt I wrote inside the my <input type="text"> but it is returning undefined , I tried many ways such as .text() or .html() or e.target.value , all of them returned undefined including this innerHTML too
$('input[type=text]').keyup(function(e){
if(e.which == 13){
alert($('input[type=text]').innerHTML);
}
});

You are mixing jQuery with Vanilla and they aren't the same. First of all, this was not going to work either way because form elements have values, not HTML. However, lets say you had tried this: alert($('input[type=text]').value);
value is a property of an html input element, but does not exist in a jQuery object. The jQuery object represents the form element, but wraps it in an extra set of properties and methods. If you truly wanted to mix them you could reference the form element from the jQuery object like:
alert($('input[type=text]')[0].value);
But it's better for legibility and consistency to stay with one or the other, which in jQuery would be
alert($('input[type=text]').val());
but as you're inside a jQuery event handler for that element, you can get it with
alert($(this).val());

Related

jQuery .find() not working correctly

I'm trying to allow some text of <p> (the comment) to be editable when the user clicks on 'Edit'.
function editComment(commentid,replyid){
$('#comment'+commentid).find('.comment-text').attr("contenteditable='true'");
}
However this is giving me an error (undefined) and I'm not sure why, as .comment-text is a child of #comment88? I'm probably missing something really simple
Your HTML DOM and jQuery looks fine and legit, however the attr function would cause a trouble. I would suggest that you apply the style using this,
$('#comment'+commentid).find('.comment-text').attr("contenteditable", true);
This will apply the attribute to your element.
Description: When you use attr() function to add or update the attribute value, you pass two parameters. One as a key and second as the value for that attribute (key). If you pass only one, it will return that attribute's value. This is the problem that gets raised in your case, the find function is working, but in the final function, instead of applying that attribute it returns the value (false IMO).

Unexpected error using an indexed element id

I'm new to javascript and jquery, and stumbled upon an issue while writing a script.
My script is generated by php code which reads lines from a file, parses it and prints them out using arrays. js then validates form input, and outputs useful messages to the user.
I have successfully used js and jquery on $('#id').blur on various elements. However when I tried doing it on my indexed element, I came across this problem.
Code:
$('#NS_IN[0]').blur(function() {
alert("Called");
CopyNStoMain();
});
I noticed that this function would never get executed. I tried looking at the variables in console.
typeof($('#NS_IN[0]')) is an object; but typeof($('#NS_IN[0]').val()) is Undefined.
In my html code, I have:
<input type="text" id="NS_IN[0]" value="" name="NS[0]">
What am I doing wrong? If the id NS_IN[0] is defined and $(NS_IN[0]) refers to an object, shouldnt $(NS_IN[0]).val() exist and hold the value of the input box?
You need to escape the jquery selector characters.
$('#NS_IN\\[0\\]').blur(function() {
alert("Called");
CopyNStoMain();
});
You already have the answer here...I don't know how to tag your question as a duplicate.
//get
bla = $('#txt_name').val();
//set
$('#txt_name').val('bla');
In jQuery, the [] works in a different way, like:
div[id^="player_"]
So, one of the solutions, is to select the items which ID starts with something:
$("input[id^=NS_IN]").val();
It works when you use a different selector, as jquery uses the [] as an attribute selector itself. So use e.g. (see fiddle: http://jsfiddle.net/rePQm/1/ ):
$('input').click(function() { alert("clicked " + this.id); });
an element selector that selects all input elements and adds the click handler to all of them. See the selectors section of the jquery documentation at http://api.jquery.com/category/selectors/ for more possible selectors .

this.is(":checked") not working

I'm using the following code to loop through all the checkboxes in my form. The boxes are gerenated dynamicaly from a php script so I won't know the names or the number of check boxes.
I need to find out which checkboxes have been ticked so I only pass those ones to the php script that handles the form.
$("#panelform input:checkbox").each(function () {
if(this.is(":checked")){
fields = fields+"&"+this.name+"="+this.value;
}
});
When the script gets to the this.is(":checked") it errors but being jquery my console doesn't show me any error messages just stops.
if I alert or console.log "this" after the first line I get the form field so I know that that much works.
try with
if($(this).is(":checked")){
since this is just a reference to the node in the DOM (and you need instead to use the jQuery wrapper to chain the method is().
Try this:
if( this.checked)
this is the plain DOM node, checked is its property to tell you if it's checked or not. Creating a whole new jQuery object just to see if a property is set is redundant.
In that contect, this refers to the DOM element, not the jQuery object - and DOM elements have no method is(). You can wrap it in a jQuery object if you want to use is method:
if($(this).is(":checked")){
or use the DOM Element's checked property:
if(this.checked){
$(this).is(':checked')
if you want to serialize your form try this
$('your-form-selector').serializeArray()

jQuery .val change doesn't change input value

I have an HTML input with a link in the value.
<input type = 'text' value = 'http://www.link.com' id = 'link' />
I am using jQuery to change the value on a certain event.
$('#link').val('new value');
The above code changes the value of the text box but doesn't change the value in the code (value = 'http://www.link.com' stays unchanged). I need the value = '' to change as well.
Use attr instead.
$('#link').attr('value', 'new value');
demo
Changing the value property does not change the defaultValue. In the code (retrieved with .html() or innerHTML) the value attribute will contain the defaultValue, not the value property.
to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426
http://api.jquery.com/val/#val2
about val()
Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.
$('#link').prop('value', 'new value');
Explanation:
Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.
This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.
For me the problem was that changing the value for this field didn`t work:
$('#cardNumber').val(maskNumber);
None of the solutions above worked for me so I investigated further and found:
According to DOM Level 2 Event Specification:
The change event occurs when a control loses the input focus and its value has been modified since gaining focus.
That means that change event is designed to fire on change by user interaction. Programmatic changes do not cause this event to be fired.
The solution was to add the trigger function and cause it to trigger change event like this:
$('#cardNumber').val(maskNumber).trigger('change');
My similar issue was caused by having special characters (e.g. periods) in the selector.
The fix was to escape the special characters:
$("#dots\\.er\\.bad").val("mmmk");
Note that the browser parses the HTML tag element and creates a corresponding DOM node object.
"Initial/starting/default value" of input:
Equals:
ONLY the initial value of value attribute of input's HTML tag element.
defaultValue property of input's DOM node object.
Is set in jQuery via:
$(input).attr("value", "42")
"Current value" of input:
Equals:
value attribute of input's HTML tag element
value property of input's DOM node object.
Is set in jQuery via:
$(input).val("42")
$(input).prop("value", "42")
See also: What is the difference between properties and attributes in HTML?
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>

jQuery .attr() and value

I want to make the following use .attr();
selectbox.options[selectbox.selectedIndex].value
sadly,
selectbox.options[selectbox.selectedIndex].attr("value")
is not the same, and seems to defeat the purpose of the .attr altogether. My main question is: How should one use nested .attr()s?
To get the value of any type of input element (including <textarea> and <select>) use .val():
var value = $(selectbox).val();
The .attr() translation would roughly be:
$(selectBox).find(":selected").attr("value");
....but just use .val() :)
The basic problem is that .attr() is a jQuery method. It's on jQuery objects, not on DOM elements directly, the same goes for almost all jQuery methods and plugins.
When using attr(), you have to be working with a jQuery object. So first select the relevant select box, then call attr() (or val() in this case, when you need the value of an input element).
var value = $(selectbox).val();
If you would like to retrieve the selected box's value using your current code simply pass it into the jquery object like so.
$(selectbox.options[selectbox.selectedIndex]).attr('value');
The reason they are not the same is because attr('value') gets the value of the value attribute directly from the original HTML code, it is not updated with the DOM, meaning if the value of value is changed after the page has loaded, either by user input (typing into an <input> element, or via manipulation with JavaScript, these changes will not be reflected in the returned value of .attr().
A better way is to use the .val() method of the jQuery object.
Edit
To get the attribute of the value from a DOM Element (i.e. not returned by the $() or jQuery() function) use the element.getAttribute() method, which is native, you would use it like this:
selectbox.options[selectbox.selectedIndex].getAttribute("value");

Categories

Resources