Determin Type of Input - jQuery - javascript

I am needing to determine the type of an element, possibly identified by the id property of it.
For example, in the following form...
<form id='my-form'>
<input type='text' id='title' />
<textarea id='comment'></textarea>
</form>
I would like to have a way to identify that $('#title') is a text box.
After some searches, I tried some thing like this, but it returns undefined.
$('#title').type
But some thing like this seems to work, I don't know why...
$('#my-form :input').each( function() {
alert(this.type);
} );
The above will give text and textarea I guess. But when I use the first, it gives undefined.
given an ID of an element, how can I find the type of it.
Thank in advance.

You can get the type of the element by writing
$("#target").attr('type');
or use
$("#target").get(0).tagName // return tag name like INPUT,TEXTAREA ..etc

input is a normal tag, you should use:
$('#my-form input').each( function() {
alert(this.type);
});
This will return undefined:
$('#title').type
Because $("#title") is a jQuery object and type is a property of HTML Element. You can get HTML Element from jQuery object like this:
$('#title').get(0).type

$('#title').attr('type') ;
OR
$('#title').prop('type');

You can use
if($('#title').is('input')){
alert('title in an input element')
} else if($('#title').is('textarea')){
alert('title in an textarea)
}

Related

Changing input type="number" - value changes, but not the front-end number [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

Testcafé - getting content of invisible <input>'s value attribute

I need to get the value of an <input>, specifically the stuff that is held inside its value attribute.
However, the input is not visible, so that seems to be a problem for testcafé.
Does anyone know how to work around that? Is there a special option you can use with the Selectors to make it work?
Thanks for helping me out, I appreciate any help!
Got it, simply declare a Selector like this let yourInputs = Selector('input[type="hidden"]'), this will get all hidden inputs and return a NodeList which you can iterate over in your test.
If you want to be more specific and select over an ID or name, do it like #lumio.
Then you can access the value in your test run with an await yourInputs.value.
I guess you mean a hidden input element as in <input type="hidden" /> and you want to receive the value before you're sending it to your Node application. You can use querySelector for this.
console.log( document.querySelector( 'input[name=test]' ).value );
<input type="hidden" name="test" value="hello world" />
For TestCafé you got the Selector-constructor which creates a selector.
As fweidemann14 pointed out, you can do the following:
const hiddenInputs = Selector( 'input[type="hidden"]' );

Javascript prompt and submit

I want to get a value from JavaScript prompt and pass it to input for finally submit it
HTML
<form id="createdirForm"><input type="text" name="" id="createdir"/><form>
JavaScript
function createdir() {
var newdirname;
newdirname = prompt('Please input the directory name:', '');
if (!newdirname) return;
$('createdir').newdirname.value = newdirname;
$('createdirForm').submit();
}
The reason why it's not working is because you're not calling the selector in your jQuery properly.
You might want to take a look at the jQuery Selector Tutorial.
Now to fix your problem, since you want to get the input and the form by the id attribute, just like in CSS, you need to use the hashtag (#) symbol.
So you would do:
$('#createdir').val(newdirname);
$('#createdirForm').submit();
Here's a working example: https://jsfiddle.net/vm4ah1L3/1/
Just a side note, you might want to add a name to your html input otherwise when you submit it to your PHP, you won't be able to retrieve the value since the name attribute is empty.
<input type="text" name="dirName" id="createdir">
And in your case, since you're declaring the variable newdirname and assign it right after, you could simply do the assignation in one line:
var newdirname = prompt("Please input a directory name: ");
It seems your jQuery selector is wrong. Try
$('#createdir').val(newdirname);
$('#createdirForm').submit();
jQuery uses the css selector logic, therefore to select an element by id you need to put the # before the selector name.
Also, to add a value to an input, you need to use val(param) with your value replaced in the param.
You have some typo and have forgotten to add #. And the function is not executed.
HTML
<form id="createdirForm">
<input type="text" name="dir" id="createdir" />
</form>
JavaScript
function createdir() {
var newdirname;
newdirname = prompt('Please input the directory name:', '');
if (!newdirname) return;
$('#createdir').value = newdirname;
$('#createdirForm').submit();
}
createdir();

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I have a text box element whose value I am trying to access using document.getElementById("id-name").value. I find that the call is returning a null instead of empty string. The data-type of the returned value is still string. Is null a string value?
<input type="text" value="" id="mytext"> is the textbox whose value I am trying to fetch using var mytextvalue = document.getElementById("mytext").value;
Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.
element1 = document.getElementById(id);
if(element1 != null)
{
//code to set the value variable.
}
fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.
For your code
var mytextvalue = document.getElementById("mytext");
mytextvalue will contain null if you have a document.write() statement before this code. So remove the document.write statement and you should get a proper text object in the variable mytextvalue.
This is caused by document.write changing the document.
It seems that you've omitted the value attribute in HTML markup.
Add it there as <input value="" ... >.
Please check this fiddle and let me know if you get an alert of null value. I have copied your code there and added a couple of alerts. Just like others, I also dont see a null being returned, I get an empty string. Which browser are you using?
This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):
var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false
and changing the console.log to alert, I still get the desired output in IE6.
I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.
ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.
try this...
<script type="text/javascript">
function test(){
var av=document.getElementById("mytext").value;
alert(av);
}
</script>
<input type="text" value="" id="mytext">
<input type="button" onclick="test()" value="go" />
if you are using external js file add <script src="fileName.js"></script> at the end before closing the </html> tag. or place <script> at the end before closing html tag .

jquery html() not working

I have an input box created by jquery like so:
val input = $('<input class="pick_date" ... />')
but the .html() method on input does not return the string entered inside the $. does anyone know why?
edit:
Ah, I understand the problem. Is there a way to get the html representation of the entire input box and not just the entry?
you are passing <input /> which is a self-closing tag.
If you were passing <input>Html here</input> (which is valid XML but not HTML to my knowledge), you could retrieve the "Html here" part with the .html() function like so:
var input = $('<input class="pick_date">Html here</input>');
alert(input.html());
In addition to your edited question:
$('<input />').outerHtml();
this should work.. :)
with this ofcourse (source):
(function($) {
$.fn.outerHTML = function() {
return $('<div>').append( this.eq(0).clone()).html();
};
})(jQuery)
I think maybe you are looking for append():
$("div#form").append('<input class="pick_date" ... />');
Just had to deal with this problem.
If you are using ASP.NET, it could be because ASP.NET changes the id names, if you add "runat="server".
So instead of doing this:
<td id="mytd" runat="server"></td>
$('#mytd').html()
Try doing this:
<td id="mytd" class="myclass" runat="server"></td>
$('.myclass').html()

Categories