JavaScript: Count inputfields in a Div - javascript

I have a <div id="inputform"> and in that div there are multiple <input type="text"> .
How can I count the number of <input> fields?

var inputFormDiv = document.getElementById('inputForm');
alert(inputFormDiv.getElementsByTagName('input').length);

Using jQuery you would be able to count the number of elements of a certain type, class, etc. using the following line of JavaScript
$("div#inputForm input").length
If you're not using jQuery, take a look at Brian's answer, it should do what you need it to.

$('#inputform input[type="text"]').length;

Related

How to clone elements and generate dynamic ids

I am cloning some form elements and want to generate for them dynamic ids so I can acces their content later on, but I don't really know how to do that, I'm a noob with Jquery/Javascript, by the way.
My html:
<tr>
<td>
<label for="ability">Ability</label><br>
<div id="rank_ability" name="rank_ability">
<select name="ability" id="ability">
<option value=""></option>
<option value="hexa">Test</option>
</select><br>
<label for="range_ability_min">Range:</label>
<input type="textbox" name="range_ability_min" id="range_ability_min" class="small_text" value="0" /> -
<input type="textbox" mame="range_ability_max" id="range_ability_max" class="small_text" value="0" /><br>
</div>
Add Ability<br><br>
</td>
</tr>
My JS:
$(document).ready(function () {
var element, ele_nr, new_id;
$('.rank_clone').click( function() {
element = $(this).prev();
ele_nr = $('div[name="'+element.attr('name')+'"]').length;
new_id = element.attr('name') + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
I setup a jsfiddle with what I got here: http://jsfiddle.net/xjoo4q96/
Now, I am using .prev() to select the element to clone which leads to those repeated 1 in the id/name attributes, how could I select it in another way (to mention: I really need to use 'this' because I need this little script in like 3 places, so I don't want to write it for an element with a specific id/class).
Also, I am counting only the element with the base name attribute so .lenght yelds 1 all the time, how would I go around counting all of them ? I guess I have to place them in another div or something but I don't know how would I go around couting them even then.
And, at last, how would I go around changing all the name/id attributes of the elements I have in the div ?
I'd appreciate any help. Thanks.
you can put the template in a hidden div like #tmpl, then clone and set the id attr, e.g.
$('#tmpl').children().first().clone().appendTo('#target').attr('id', 'the_generated_id');
Update
Demo of the template way: http://jsfiddle.net/xjoo4q96/1/, though it would be quite easy to adjust the code to clone the first component that already existed.
BTW, principally, id should be unique, thus the sub-element in the cloned component should use other attribute, like class or certain data- attribute, like those used in the updated fiddle.
Also you might want to call event.preventDefault() as you're clicking an <a>
You are searching already with the wrong name, since it still has the number attached. So delete it first, search for element which have a name attribute starting with this name and then use this base name to create a new one.
$(document).ready(function () {
var element, ele_nr, new_id, base_name;
$('.rank_clone').click( function() {
element = $(this).prev();
base_name = element.attr('name').replace(/[0-9]/g, '');
ele_nr = $('div[name^="'+base_name+'"]').length;
new_id = base_name + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
And to answer your last question: you can not go around changing all ids of inner elements, it would be invalid HTML. In principal you can do the same with every id, like adding a number. If you have to do the same with all the name attributes depends on what you want to do exactly. If you have to distinguish between the first and second input, which I suggest, you have to change them too.
try to use cloneJs, it's clone ids, names input, and parametre inside functions ids of input must be like id_foo_1, id_foo_2 ,,,, and name be like inputName[0][foo], inputName[1][foo] https://github.com/yagami271/clonejs

Remove value attribute from input tag

I have one input field having no value field ( that will be added later using jQuery )
<input type=hidden>
Once I execute some function to add value to the input field I get
<input type=hidden value="123">
I want remove that value field from input field later. How can I do that?
Presently I am using the following jQuery function:
$('input').val('');
and using that I get
<input type=hidden value>
But I want
<input type=hidden>
How Can I achive that?
Thanks...
jQuery's removeAttr removes attributes.
Try: $("input").removeAttr( "value" );
Edit 2018-09-11:
Since jQuery isn't necessary to do this, and the title doesn't specifically ask about jQuery (although the tags do), here's the solution in plain JavaScript:
document
.querySelectorAll( "input" )
.forEach( ( input ) => {
input.value = "";
input.removeAttribute( "value" );
} );
However, as #cookie-monster originally said: you probably shouldn't be removing DOM attributes. Consider rethinking your application.
You are looking for somehing like:
$('input').removeAttr('value');
use removeAttr()
$('input').removeAttr('value');
You can use:
$('input').removeAttr('value');
You can use the .removeAttr() method. This method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.
$('input').removeAttr('value');
To remove 'value' attribute from all inputs you can use
$('input').removeAttr('value');
You can also use input ID.
Example:
$('#Input_Id').removeAttr('value');
Or class for remove attribue
Example:
$('.Input_Class_Name').removeAttr('value');

How to get html content of a input tag?

I have an input tag:
<input type="text" value="04/09/2013" class="date-time-date width-100 hasDatepicker" name="booking_info[to_time_24_date]" id="to_time_24_date" readonly="readonly">
i need to get all the content in input tag (all content shown above) but when i use
$('#to_time_24_date').html();
it returns nothing. How can i get this content?
Try this:
document.getElementById('to_time_24_date').outerHTML;
Use this simple method in order to get all of your input field HTML:
$('#to_time_24_date').get(0).outerHTML;
I have made a JsFiddle Test Demo for you, Please follow this link. It will give the same thing you are looking for, in alert.
http://jsfiddle.net/jpaYK/
You may try the outerHTML property.
$('#to_time_24_date').get(0).outerHTML
you can use outerHTML
$('#to_time_24_date').get(0).outerHTML; // $('#to_time_24_date')[0].outerHTML;
Demo: Fiddle
without jQuery
document.getElementById('to_time_24_date').outerHTML
html() gets the inner HTML, HTML of the elements inside this element.
Check the answer here:
Get selected element's outer HTML
The accepted answer uses a nice trick in the answer to this question. It creates another element (but doesn't add it to the page), clones the element it wants inside the created element, and then gets the inner HTML of the created element, which is the HTML of the clone, which is the same HTML of the element we want.
$("<div>").append($('#to_time_24_date').eq(0).clone()).html();
// or
$("<div>").append(document.getElementById('#to_time_24_date').clone()).html();
However, see other answers as well, turns out there is a simpler way you can try too, there's a property outerHTML you can use as:
$('#to_time_24_date')[0].outerHTML
Which has decent browser support as per:
https://developer.mozilla.org/en-US/docs/Web/API/element.outerHTML?redirectlocale=en-US&redirectslug=DOM%2Felement.outerHTML
var html = "<input";
$.each($("#"+to_time_24_date)[0].attributes, function(i, attr){
html += ' '+attr.name+'="'+attr.value+'"';
});
html += " />";
alert(html);
jsfiddle
<input type="text" value="04/09/2013" class="date-time-date width-100 hasDatepicker" name="booking_info[to_time_24_date]" id="to_time_24_date" readonly="readonly">
This does not have any "Content" or "HTML" it does have attributes, and you can get the attributes with the attr method from jQuery.. $('input[type="text"]').attr('id'); would return the id attribute.
If you are just looking for the entered value of the input tag (what is typed in) then use $('input[type="text"]').val(); to get the value.
I hope this helps
here's a jsfiddle example
http://jsfiddle.net/LUep8/

How to select a parent element without any class or id using jquery?

I have the following code:
<div>
<label for="fsc_name1">Name:<span class="required"> *</span></label>
</div>
<div>
<input style="text-align:left; margin:0;" type="text" id="fsc_name1" name="fsc_name" value="" size="60">
</div>
It's a piece of a contact form and I need to be able to hide some of it's elements if a specific element is selected. So lets say I want to hide the two divs above. There's no id or class and I can't give them any. All I have is unique values "for="fsc_name1"" (<label>) and "id="fsc_name1"" (<input>)
Easy! Just use jQuery parent(). See docs: http://api.jquery.com/parent/
$('#fsc_name1').parent().hide()
$('label[for="fsc_name1"]').parent().hide()
You can also combine your selectors to save space. See docs: http://api.jquery.com/multiple-selector/
$('#fsc_name1, label[for="fsc_name1"]').parent().hide()
You can use a mix of atttribute selector, id selector and .parent() to solve this problem
$('label[for="fsc_name1"]').parent().hide()
$('#fsc_name1').parent().hide()
For a start, id="fsc_name1" is a class selector, you can do it via
$('#fsc_name1').parent().hide();
But, I think for your scenario, you're wanting something like this...
// This can be an array of elements
var selector = 'fsc_name1';
$('label[for=' + selector + ']').parent().hide();
$('#' + selector).parent().hide();
No jQuery version:
document.querySelector('[for=fsc_name1]').parentNode.style.display = 'none';
document.querySelector('#fsc_name1').parentNode.style.display = 'none';
Please have a look on http://jsfiddle.net/2dJAN/31/
$('#fsc_name1').closest('div').css('border','1px solid red')
$('#fsc_name1').closest('div').prev('div').css('border','1px solid green')
Note: Exactly I am not able to understand your question. So I add the border to the div's in example. If you want to hide, instead off .css you add .hide()that will hide the div.
Let me know if you have any questions.
Use the .parent() method.
$('#fsc_name1').parent().hide();
$('label[for="fsc_name1"]').parent().hide();

jQuery selector bug? composed selector vs. simple selector & find()

Something is very awkward about my situation... i have something like this:
<div id="selector">
<input type='radio' />
<input type='radio' />
<input type='radio' />
</div>
if I use $("#selector input[type=radio]") all three elements are found, but if I use $("#selector").find("input[type=radio]") or even find("input") only the first one is found.
Is this a bug in jQuery? Am I not using find() properly?
Clarification : I want to use find() to get all the inputs, but anything I try finds only the first one.
edit: i'm using jquery 1.3.2
What you really want is:
$("#selector > :radio")
As for why you're getting only one, I'd need to see the actual code that's being run because find() doesn't stop at one and will find all matches so it may be how you're using it afterwards that is the issue.
The two code fragments should return the same result.
Are you saying that when you run the following code, the first alert will show "3" and the second "1" ?
var a = $("#selector input[type=radio]");
var b = $("#selector").find("input[type=radio]");
alert(a.length);
alert(b.length);
Can you please verify?
Try
$("#selector").find("input[type=radio]")
See here
All the three returns the same result!
$(function() {
console.log($("#selector input[type=radio]")); // 3
console.log($("#selector").find("input[type=radio]")); // 3
console.log($("#selector").find("input")); // 3
});
$("#selector").children("input[#type=radio]")

Categories

Resources