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

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');
}
});

Related

event.target.name is undefined

I am trying to use e.target.name in react to set the state as I have done before, however e.target.name seems to be undefined for some reason and I can't figure out why, if any one has a suggestion it will be welcome.
thanks!
<li
onMouseEnter={this.handleMouseEnter.bind(this)}
name="HOME"
id="some id"
style={main.element}
>
HOME
</li>
my event handler has only a debugger for me to play with
handleMouseEnter(e) {
debugger
}
and when i try to get the value of the name property i get undefined
e.target
//<li name=​"HOME" id=​"some id" style=​"padding:​ 10px;​">​HOME​</li>​
e.target.name
//undefined
e.target.id
//"some id"
name is an attribute and needs function getAttribute(...) to be fetched. As #Ele has pointed out, the suggested solution would be
var name = e.target.getAttribute('name'); //'HOME'
Form fields are the elements who must use the attribute name.
The JS engine will automatically set that attribute within the form elements (input, select, etc).
document.querySelector('li').addEventListener('click', function(e) {
console.log('Directly: ' + e.target.name);// prints null
console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});
document.querySelector('input').addEventListener('click', function(e) {
console.log('Directly: ' + e.target.name);
console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});
<input name="ele" placeholder="Click me!">
<li name="ele">Click me!</li>

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

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>

Grab the value of latest textbox on a particular variable having multiple textbox with same ID

I want the value of last textbox to be grabbed by the varialble on multiple textbox with same ID.
HTML
<input type="text" id="get"><br>
<input type="text" id="get"><br>
<button id="grab">Click</button><br>
SCRIPT
$("#grab").click(function(){
var value = $("#get").val();
});
Or, a way to delete the first textbox might also work. Working Example
Your HTML is invalid: HTML elements can't have the same id attribute.
Use the class attribute, instead.
You can then use .last() to get the last element that matches the .get selector:
$("#grab").click(function(){
var value = $(".get").last().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="get" value="foo"><br>
<input type="text" class="get" value="bar"><br>
<button id="grab">Click</button><br>
(I added the value attributes for demonstrative purposes. Obviously, they can be removed.)
If you want to get the first element's value if the second one is empty, you could do this:
$("#grab").click(function(){
var firstValue = $(".get").val(); // `.val()` gets the first element's value by default
var secondValue = $(".get").last().val();
var result = secondValue || firstValue;
alert(result);
});
If you don't have any control on ids you should use following solution. If you can change the ids you should change them.
You approach will not work because the id is not unique. It will always get the first input.
$("#grab").click(function() {
// var value = $(this).prev("input").val(); // Will work when there is no `<br>`
alert($('input[id="get"]').last().val());
});
Here $('input[id="get"]') will get all the elements having id get and last() will get the last element from it.
Demo: https://jsfiddle.net/orghoLzg/1/

how can i console.log how the #form values will be sent?

i know we can manally log any input value by its selector
console.log('inputName='+$('#inputId').val()+'....)
But is there -simpler- a way to log all input values? if it's posible to do it when any input changes
You can use serialize to serialize the form elements to a string for logging. It follows the same rules for including or not including elements as normal form submission. The only caveat is that the content of input type="file" fields isn't serialized, for perhaps obvious reasons.
To fire it when any of the inputs changes:
$("form :input").change(function() {
console.log($(this).closest('form').serialize());
});
Live demo using the form shown in the documentation
You may get in form of query string using $("form").serialize().
This would log the form every time anything changes:
$("form :input").change(function(){
console.log($("form").serialize());
});
Edit:
Removed my focusout suggestion, as I realized that change is actually only fired when the element looses focus.
I made this little component:
$("form :input").change(function() {
var fields = $(this).closest('form').serialize();
serialize_to_console( fields );
});
/*
SERIALIZE TO CONSOLE
Transforms string to array and show each param in console if not empty */
var serialize_to_console = function( serialized ) {
var splited_serialized = serialized.split('&');
$.each( splited_serialized, function(index, key) {
var input = key.substr(0, key.indexOf('='));
var value = key.substr( key.indexOf('=') + 1 );
if( value !== '' )
console.log( '[' + input + '] = \'' + value + '\'' );
});
}
Enjoy!

jQuery checkbox selector question

Given some markup where there are a series of inputs (checkboxes) at an arbitrary depth, how can I determine if a given input is checked based on its value:
<ul id="root_node">
...
<li>
...
<span>
<input value="val_1" ... />
...
<input value="val_2" ... />
...
So, what I need is: given root_node and an input value (e.g. val_2), I want to determine if the corresponding checkbox (somewhere underneath root_node) is checked.
You can jQuery selections based on attributes: http://api.jquery.com/attribute-equals-selector and the :checked 'pseudo class'
$('input[value="val_1"]:checked')
so you could do:
if $('input[value="val_1"]:checked').val() !== undefined) {
// do something
}
Hope this help,
Martin
You can do something like:
var context = "root_node";
var value = "val_2";
var checked = $("input:checkbox[value='" + value + "']",
$("#" + context)).attr("checked");
If the context never changes, you can shorten the above into:
var checked = $("#root_node input:checkbox[value='" + value + "']")
.attr("checked");

Categories