jQuery get value from checked element with a given name - javascript

I've got an input like so:
I'd like to use jQuery to grab that element, and add the function call foo() to the change event. Currently I can get it done, but there are two hacks involved. My (working) code:
$(":input[name*=myfield]").change(
function( $(":input[name*=myfield]") ) {
foo();
});
)};
There are two hacks in there I'd like to eliminate.
Keeping in mind that the input names are multidimensional arrays, how can I use the :input[name=somename], versus [name*=someone]? I'd imagine it's faster using an exact name rather than *=, but I can't get the escape sequence correct for the brackets on the multidimensional arrays.
Can I chain the call together so that I don't have to select the element twice? Is the standard practice for that to select the HTML element into a var, then use that var? Or can I chain it together?
Thanks for the help. Still working on getting my footing in JS/JQ.

1 - to escape brackets and other meta-characters, use \\[. See Selectors.
2 - $(":input[name*=myfield]").change(foo);

What's wrong with this?
$("input[name=somename]").change(function(){..});

In your html elements use the data-* like so
<input type="checkbox" data-name="box" name="myName[0][1]" checked="" />
then within jQuery
$('input[data-name=box]').click(foo);
function foo()
{
//this = input element
}

Related

Javascript selector with Regular Expression

I would like to add an event listener to 2 buttons. Their ids are:
authCreateAcctConfirmNoBtn
authCreateAcctConfirmYesBtn
How would I do the following, I imagine I am close:
authCreateAcctConfirm(No|Yes)Btn.addEventListener('blur', function() {...
I don't know how to tell the browser that the object to attach to is a regular expression?
You need to select the elements first. This is done via document.querySelector.
I would avoid crazy Regex magic and choose the straightforward way. The easiest solution would look like this:
document.querySelector("#authCreateAcctConfirmYesBtn").addEventListener("blur",func);
document.querySelector("#authCreateAcctConfirmNoBtn").addEventListener("blur",func);
function func(){
/* stuff here */
}
To select both at once, you could use querySelectorAll and use this selector:
var elements = document.querySelectorAll("#authCreateAcctConfirmYesBtn,
#authCreateAcctConfirmNoBtn");
You now have to iterate over the returned NodeList resultset with a straightforward for loop or a borrowed Array method:
Array.prototype.forEach.call(elements,func);
Here you get the element handed over as first parameter in func.

Loop though DOM with jQuery to get some data- attribute value

This seems like a simple thing, but I keep getting "undefined"
I am trying out the "data-" HTML5 attribute and I am looping through a bunch of div tags that look like this:
<div id="myEvent"
data-scheduledOn="1399985100000"
data-eventStatus="3">
And I am looping through a bunch of these like this:
$('[id="myEvent"]').each(function(index, divItem) {
alert($(divItem).data("scheduledOn"));
}
But I keep getting "undefined" If I do this (get the attribute) it works fine:
alert($(divItem).attr("data-scheduledOn"));
So What am I missing?
http://api.jquery.com/data/
"The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."
At least at this point in time, to use the .data function you have to attach the data using the function before you can read it back using the .data function.
If you need to read pre-existing data use the .attr or .prop functions.
It seems as though It is a naming problem as Hamza Kubba suggested, but just a bit different...
if I changed the name of the data attribute to "data-scheduled-on" I can retrieve it by .data("scheduledOn") OR using data-scheduledon and .data("scheduledon") also works.
So don't use CAPS for data- names is the moral of this story!
Please note that per HTML 5 specs, the attribute name should not contain any uppercase letters and some browsers such as FF & Chrome will change any uppercase letter to lowercase. That's why the following demo works if you access the data attributes with lowercase names:
http://jsfiddle.net/fiddleyetu/5LdQd/
$('div.myEvent').each(function(index, divItem) {
console.log($(divItem).data("scheduledon"));
console.log( $(divItem).data("eventstatus") );
});
Ans since you cannot have more than one element on a page with the same ID, I have used a class selector for the demo.
MORAL: Do not use UPPERcase; your browsers may not always be that 'understanding'.

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

JavaScript JQuery String Var to show in a field

I'm working with JavaScript JQuery, and when i try to show the content of the vars in a field, it doesn't work.
There is my code:
function editEvolution(pos, nature, desc, di) {
$('#diE').val(di);
$('#natureE').val(nature);
$('#descE').val(desc);
$('#BtnAddEditEvo').attr('value', "Update");
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution("+pos+")");
}
Thank's in advance for help.
the value of fields $('#diE'), $('#natureE') and $('#descE') doesn't change if the vars nature, desc, are strings but it works if it is a number
The problem is that you are mixing the worst from both the native JS, inline JS and jQuery worlds. You NEVER EVER put code inside a string, period. If you do it, you are doing it wrong.
So.. how to do it properly?
$('#BtnAddEditEvo').val('Update').on('click', function() {
doEditEvolution(pos);
});
In case you call editEvolution multiple times on the same object, add .off('click') before the .on(...) call to unbind previous handlers.
First do not use attr to set onclick...
I will explain what is wrong
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution("+pos+")");
if pos="foo", it will render as
<div onclick="doEditEvolution(foo);"></div>
See the problem? It is looking for a variable foo. You would need to add quotes.
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution('"+pos+"')");
^ ^
Why does a number work? Because numbers do not need quotes. It makes a valid call. It renders as:
<div onclick="doEditEvolution(3);"></div>
What you need to do is use jQuery the right way and use events.
$('#BtnAddEditEvo').on('click', function() { doEditEvolution(pos); });
and you should set value with .val()

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources