The code below is adding a placeholder to my #e_newsletter_email div. However I have added an additional signup box for the e-newsletter and the placeholder is not showing up on the second one. Is there a way to apply this code to work on both signup boxes?
jQuery(function($) {
$('#e_newsletter_email').attr( 'placeholder', 'You Email Address' );
});
I have tried to add this code to to force the id to add a class but again this only works on the first id. Any other thoughts?
jQuery(function($) {
$('#e_newsletter_email').addClass('e_newsletter_email');
});
Thanks
An Id can only be used once. Use classes for elements that do not need to be uniquely identified.
After some help from #mark.hch we where able to figure out how to create a workaround. Below is the final code:
<script type="text/javascript">
jQuery(function($) {
$('input').each(function() { if($(this).attr('id') == 'e_newsletter_email') { $(this).addClass('e_newsletter_email_custom'); } });
});
jQuery(function($) {
$('.e_newsletter_email_custom').attr( 'placeholder', 'You Email Address' );
});
</script>
First we needed to loop through each id and add a new class to the e_newsletter_email (which was being used twice). Then once we added the class to the id we where able to update the original function to use class instead of id and everything worked perfectly!
The true answer to the question is to use a class instead of an ID for both fields. As mentioned in the comments, an ID should be unique to each element on a page. In this case, however, the elements only contained an ID and the question then becomes how to add a class to the elements so a future selector can grab them all (or both) to manipulate them.
Using the ID selector $('#e_newsletter_email') only selects one element (as jQuery assumes there is only one element with that ID). So we need a more general selector - in this case, both elements are inputs, so the selector $('input') should grab at least those elements.
Since there could be more inputs on the page than the ones in question, we then need to filter out the ones we want; in this case, we compare the ID attribute of the elements (since we know, even though they're supposed to be unique, two actually contain the same ID).
Grabbing the ID of the element will work even if there are multiple elements with the same ID ($(this).attr('id') will always display the element's assigned ID, even if not unique).
So the code becomes:
//loop through all inputs
$('input').each(function() {
//if the input currently iterating over has the ID in question
if$(this).attr('id') == 'e_newsletter_email') {
//add the class for the input
$(this).addClass('e_newsletter_email_custom');
}
});
Related
I am working with jira and there are two buttons with the same id and class. Both are submit button, one at top and one below and when i use the below jquery only the first one is captured while clicking. Intention is to make comments testfield mandatory.
Only the top one is working..
<script>
AJS.toInit(function () {
AJS.$("#next").click(function(e){
var comment=AJS.$("#jira #page #content .aui-page-panel .aui-page-panel-inner .aui-page-panel-content #bulkedit .form-body .aui .comment-input #comment").val();
if(comment==""){
AJS.$(".bulk-affects").append("<br/><div id='resErrror' style='color:red;margin-left:30px'>Comment is mandatory</div>");
return false;
}
});
});
</script>
Please help me out with to capture both the next button to work for this script
ID's should be unique, so you should only use a particular ID once on a page. Actually when you try to call the element using id code only calls the first element. Classes may be used repeatedly
querySelectorAll will find all ID's
const allButtons = document.querySelectorAll('#next');
for (let button of allButtons) {
$(button).click((e) => {
// Do your magic here
})
}
Remember: A webpage element has certain inalienable rights; having a unique ID is one of them. Prevent html element identity theft by ensuring that every element on your webpage that needs an ID has a unique one.
But Classes can be repeated.
I currently have about a dozen html buttons on a page, all with a unique value attribute assigned to them.
Firstly, I want to be able to get the values of these buttons and assign them into an array. Here is my code:
var myArray = [];
$("#buttonID").each(function(){
myArray.push($(this).attr("value"));
});
This works, however only takes the value from the first button, and then ignores the rest, despite them all have the same ID. Have I done something wrong with my .each() ?
Once I have solved that, I would like to then modify the above to only add values of those buttons with ".active" classes on them. i.e a user has selected them.
Your selector represents an ID hence the #this why it picks only one because ID's are supposed to be unique, you need to pick them by class name like .className after assigning this class name to all of your buttons
have a loonk at this http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Let's say you decided to use a common class for your buttons instead of an ID. Example:
<button class="my-class".......
There's a wonderful jQuery method that would put the values of all the button's with this class in an array like so:
var myArray = $('.my-class').map(function() {
return this.value;
})
.get();
I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO
I have a couple of drop down boxes with ids country1, country2, ... When the country is changed in a drop down the value of the country shoudl be displayed in an alert box.
if I add the onchange handler for one box like this it works fine:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
But I need to do this dynamically for all drop down boxes so I tried:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
This doesn't work. No syntax error but just nothing happens when the seleted country is changed. I am sure that the each loop is performed a couple of times and the array contains the select boxes.
Any idea on that?
Thanks,
Paul
The reason .live() existed was to account for elements not present when you call the selector.
$('[id^=country]') .each(function(key,element){ iterates over elements that have an id that starts with country, but only those that exist when you run the selector. It won't work for elements that you create after you call .each(), so using .live() wouldn't do you much good.
Use the new style event delegation syntax with that selector and it should work:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Replace document with the closest parent that doesn't get dynamically generated.
Also, consider adding a class to those elements along with the id attribute.
Instead of incremental ids I'd use a class. Then the live method is deprecated but you may use on with delegation on the closest static parent or on document otherwise.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
You don't need an each loop this way; plus events are attached to all the elements in the jQuery collection, in this case all .country elements.
$("a[href*='http://www.google.com']").attr('id','newId');
Can only reference it by href.
Yes, that's the correct way to add an id attribute to an element that doesn't already have one.
However you should ensure that there's only one matching element, as it's incorrect to have two elements with the same ID on a page, e.g.:
$("a[href*='http://www.google.com']").first().attr('id', 'newId');
This would, of course, still leave you with the problem of what to do with the remaining matching elements, if any. A possible solution would be:
$("a[href*='http://www.google.com']").attr('id', function(index, attr) {
return 'newId_' + index;
});
which will assign the elements the IDs newId_0, newId_1, etc.