for example I have many input elements with name "test_(1...100)". I want to find all of them.
I just so happened to have had the exact same problem, this is how I solved it:
var divs=document.getElementsByTagName("div");
var re = /test_[\d]+/i;
for (thediv in divs) {
if (divs[thediv].id != null && divs[thediv].id.match(re)) {
//your stuff here
}
}
And as slhck pointed out, to make the chance of getting an answer bigger you should start accepting some answers to your questions. This is done by using the Green checkmark next to every answer.
Use RegularExpressions. An online tool might help.
The expression you need will be something like:
test_[\d]+
If you are using jQuery, then you can use .filter() with a function:
$('input').filter(function(){
return this.name.match(/^test/);
}).css({background: 'red'});
See DEMO.
If you are not using any library that would help you with that then you have to iterate over every input element that you find and match its name with your regex on every iteration.
Related
I'm using PHPStorm and have the following js code
$('#id'.val($('#id'.attr('default'));
The idea is to reset the value of a input field to it's default which is set in default attribute of the input element.
Now the IDE is suggesting me to avoid duplicate selectors.
Though it is working I'm interested in finding out what is the best way to optimize this code line?
Not exactly what you asked for but more future proof using data and not an attribute. You could even store complex data or other information in there as well like "originalvalue" or "lastchangedvalue" etc.
Storing in an attribute is fine however I prefer to store things like this in the data of the element like:
<myelementtag id="myid" data-defaultvalue="defaultvalue" />
You then access it like:
$('#myid').data("defaultvalue");
For example:
var myElement = $('#myid');
myElement.value = myElement.data('defaultvalue');
Want to reset the default?
var mynewdefault = "mynewvalue";
myElement.data('defaultvalue', mynewdefault);
Since you asked only one selector and one line code, please use like this as stated in jQuery documentation (middle section):
$("#id").val(function(index,value) {
return $(this).attr('default');
});
or if you want to avoid $(this):
$("#id").val(function (index, value) {
return this.getAttribute('default');
});
JSFiddle
And yes, as other members have pointed out, it would be better if you use data attribute (data-defaultValue) instead.
This is a more compact solution:
var id = $('#id');
id.val(id.attr('default'));
You really don't need to use $(...) every time.
Store your jQuery element in a variable:
var $id = $('#id');
$id.val($id.attr('default'));
This is what I am trying to achieve: If a input image is clicked, and the input image matches word (referenced in array) run a previously ran function again.
I've messed around with the code but can not seem to figure out why it's not working.
I'm new enough to javascript so please excuse that lack of knowledge and terminology :P
You need to use array.indexOf(element)
Checkout this question
How do I check if an array includes an object in JavaScript?
Update: for your case yo better use array.some
randomwodrz.some(function(item){return item.word === 'word_to_match'})
I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }
Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});
How would one adapt this jquery plugin so that it counts down from how many words your allowed/you have remaining, instead of counting up to how many your allowed.
www.javascriptkit.com/script/script2/enforceform.shtml
Thanks in advance.
There is also a very simple way to do it without a maxlength attribute. (This example uses 200 as the maximum characters).
$("#YourTextareaId").keyup(function () {
var i = $("#YourTextareaId").val().length;
$('#IdOfCountdownDisplay').val(''+200-i+'');
A nice thing to remember when coding, is that a simple equation can get rid of a whole lot of complicated code.
open the maxlength.js file and put this
$field.data('$statusdiv').css('color', '').html( $field.data('maxsize') - $field.val().length )
instead of this:
$field.data('$statusdiv').css('color', '').html($field.val().length)