I have a javascript program to filter a list of things in a HTML select control by typing a regular expression into an input (text) box. I can do the following to correctly filter a specific select control:
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist(document.myform.myselect);
filter.set(this.value);
});
});
but I have used a custom attribute (something one can now do in HTML5) called data-filterable. The attribute will store the name of the select control that is to be filtered so that JS can use the name of the control to filter the list. This would be a good idea because I will have a general function to filter any select box rather than a specific one.
Any ideas how I do this? I need something like this in the HTML:
<input data-filterable='{"to":"#selectbox1"}' size="30" type="text" />
but I'm not sure exactly what I'm doing here and what to do with the JS.
Thanks guys :).
Try this:
<input data-filterable="#selectbox1" size="30" type="text" />
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist($($(this).data('filterable'))[0]);
filter.set(this.value);
});
});
To break down the expression $($(this).data('filterable'))[0]:
$(this) wraps this in a jQuery wrapper. In our context, since it's a jQuery keyup event handler, this references the <input> DOM node.
$(this).data('filterable') retrieves the contents of the data-filterable attribute as a string. In our case, it's #selectbox1.
After that this string gets passed in to jQuery as a selector: $($(this).data('filterable')).
Finally, we take the 0'th element of the returned array which should be the DOM element of the target selectbox. Of course, if there isn't a selectbox which fits the selector this will fail rather miserably. If you suspect that this is a real scenario, check the .length of the returned array first.
Related
I am trying to move text from inside a div into the value from an input field but I'm getting [object Object] as the output. Can anyone explain why?
input = $('#input').contents();
$('#output').val(input);
Spencer.
The .contents() method won't give you the text, but an object with a collection of the elements it contains. You sould use:
val method:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea.
text method:
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method.
The line you're looking for is:
$('#input').val($('#div').text());
and can be decomposed like this:
var textToMove = $('#div').text();
$('#input').val(textToMove);
Here is a full example:
function move(){
$('#input').val($('#div').text()); //copy text
$('#div').text(''); //erase text
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input' type='text' value=''>
<div id="div">Hello, Spencer</div>
<button onclick='move()'>Click to move text</button>
First get the text content with
$("#d").text()
Add this to input like
$("#y").val($("#d").text());
Now you can remove text of div like
$("#d").text("")
$("#y").val($("#d").text());
$("#d").text("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="d">text</div>
<input type="text" id="y"/>
Note:
Given a jQuery object that represents a set of DOM elements, the .contents() method allows to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. and the results includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Here
That's why you are getting object. you really need to use .text() here to get the text contents only.
The contents() you were trying to use is defined by the jQuery documentation as
To get the children of each element in the set of matched elements,
including text and comment nodes
So, contents() is returning en entire object with all those children, comments and etc... that's why: [Object Object]. If you use console.log($('#input').contents()) you will be able to see the entire object in the console.
So, in that case, it's better to use text(), that get only the text content of the element matched.
After getting the text, then set it to the input with val();
the example below shows this. (I added a timer just to better represent the code working, you can remove it and let only the code that is inside).
Also, if you want to keep the text in the div, remove the part where I used .text('');
setTimeout(function(){
input = $('#input').text();
$('#output').val(input);
$('#input').text('');
}, 1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='' id="output">
<div id="input">Abcdef 1234567890</div>
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
I have an array of input text boxes simplified as bellow:
<input type="text" name="quantity[3]" value="0">
<input type="text" name="quantity[6]" value="0">
<input type="text" name="quantity[7]" value="0">
<input type="text" name="quantity[11]" value="0">
Either of the two ways is acceptable for me, but I don't know how to do even one of them:
When the 3rd input box (with has index 7) is changed, either of the two alert()s is acceptable for me:
7 (because the real index of the 3rd text box is 7)
2 (because probably it will be counted from 0 and thus its index will be 2)
My code that doesn't work is:
$(document).ready(function(){
$('input[name^=quantity]').change(function(){
alert($(this).index());
});
})
Link: http://niamco.com/cp/problem.html
It is expected that when the user changes any of the Quantity text boxes, the text box's val() be alerted as well as their correct index(). We see that the val() is outputted correctly, but the index() is always returned 0.
As the val() is correct, we should be sure that jQuery is loaded well and working. So why shouldn't index() be true?
Strange is that as I've researched, both val() and index() are jQuery functionalities. If val() was javascript base, it could be accepted. But now, one jquery Base function works, and the other does not!
.index() gets the element's current position relative to it's siblings. You should use a regex to get the number between [ and ] in the input's name.
Use this instead:
$('input[name^=quantity]').change(function () {
var index = $(this).prop('name').match(/\[(.*?)\]/)[1];
console.log(index);
});
Here it is working: http://jsfiddle.net/u8HRq/1/
UPDATE: Based on your update here's a working fiddle: http://jsfiddle.net/qbmAU/2/
First off ids should be unique so I've changed them to classes and updated the selector for the change event.
I've also got .index() working:
$(this).index('.quantity')
index() usually works by returning the position relative to the matching siblings which is why mine and j08691's answers were working. However, if the elements aren't siblings then you can pass a selector as an argument. This returns the index of the current element relative to the matched elements.
This gets both:
$('input[name^=quantity]').change(function () {
console.log($(this).index(), +$(this).prop('name').match(/\d+/g));
});
jsFiddle example
$(this).index() is the true index
+$(this).prop('name').match(/\d+/g) is the index from the attribute
Update: After you updated your question to show the code you're really using, this should help you:
$('input[name^=quantity]').change(function () {
console.log($(this).closest('table').find('input[name^=quantity]').index($(this)), +$(this).prop('name').match(/\d+/g));
});
+$(this).prop('name').match(/\d+/g) still works to get the index from the attribute
$(this).closest('table').find('input[name^=quantity]').index($(this)) but you'll need this format using .index() to get the index of the input elements since they're not siblings of each other. You need to pass an argument for the collection of elements you want to compare them against, in this case $(this).closest('table').find('input[name^=quantity]').
<input name="Indian_Karnataka_Bangalore" value="Bangalore" />
<input name="Indian_Andhra_Hyderabad" value="Hyderabad" />
<input name="Indian_Kerala_Trivandrum" value="Trivandrum" />
<input name="Indian_Maharashtra_Mumbai" value="Mumbai" />
At a given time, only one input element will be present in the DOM. How will I know the name of the specific input element name? I don't want to depend on values as it might change.
Using jQuery.
The INDIAN term will be static in every input element.
Actually i am trying to validate the input elements. DOM will have all the elements but at a given time only one element will be active and that element should have some value in it.
var $inputs = $('input[name*="Indian"]'),
inputsName = $inputs.attr('name');
You can use the same selectors as you would CSS.
Chris Coyier wrote a piece on attribute selectors here
var indianInputs = $("input[name^='Indian']");
//Matches all input elements whose name attrributes 'begin' with 'Indian'
This differs than the one posted by #ahren in that his selector will match all input elements whose name attribute contain the string 'Indian'.
indianInputs.attr("name");
Would return the first matched element's name attribute's value, which, for your markup will be Indian_Karnataka_Bangalore
To find the names of all indianInputs, you must iterate over all matched elements
var indianInputNames = [];
indianInputs.each(function() {
indianInputNames.push($(this).attr("name"));
});
$('input[name="element_name"]')
You have a lot of ways to select by the name of the attribute check http://api.jquery.com/category/selectors/attribute-selectors/
Try
var name = $('input[name^="Indian_"]').attr('name')
Have you tried the filter function? Something like this:
$('input:visible')
.filter(function() {
return $(this).attr("name").match(/^Indian/);
});
This will return an array of input elements whose name starts with "Indian".
There is a good example here: https://stackoverflow.com/a/193787/1237117.
Hi I am trying to get the HTML of INPUT tag. But unable to..
<input type="checkbox" name="_QS4_CNA" id="_Q0_C7" class="mrMultiple" value="NA">
<label for="_Q0_C7">
<span class="mrMultipleText" style="">None of these</span>
</label>
</input>
And I am trying access as
var dat=$(':checkbox#_Q0_C7').html();
alert(dat);
But i cannot access this. Please help me on this..
The ".html()" method gets the contents of an element, and not the element itself. In your case, the problem is that your HTML is invalid. An <input> tag cannot have content. As far as the browser is concerned, the tag ends where the <label> tag starts, and the browser just ignores the closing tag.
Note that when you've got an "id" attribute to use to find an element, you don't need any other qualifiers in the selector (like ":checkbox"). Just "#_Q0_C7" is all you need, because "id" values have to be unique anyway.
edit — Note that if all you want is to get some attribute (like the value or the "checked" status) from the element, you can certainly do that:
var $cb = $('#_Q0_C7');
var isChecked = !!$cb.prop('checked'); // force a real boolean value
var value = $cb.val();
You can try accessing the RAW underlying DOM element and use its innerHTML property.
var dat = $(":checkbox#_Q0_C7")[0].innerHTML;
But like mentioned by Pointy, that might still get you nothing. Not sure what (if any) input elements have actual siblings.