javascript variable for jquery script - javascript

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

Related

select a string after a substring in an element's class name

I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);

How to pass an array id into jquery selector?

I have an element with an array id id="x[]" that vary depending on the number of elements that I have on a database. It's basically a x button to delete a certain table row in the database.
<div align="center" id="x[]" class="x">
<img src="x 2.png" alt=""></div>
Problem is, I don't know how to pass this id into the jQuery selector. I want to change the form action to delete the row and create an hidden input to get the paramater I need from another field with an array id id="codsinmov[]" with the same index as x[]. What I have so far is:
$(document).ready(function(){
for(var i=0; i<x.length; i++) {
$('#x[i]').click(function(){
var $hiddenInput = $('<input/>',{type:'hidden',id:codsinmovesse, name:codsinmovesse});
$hiddenInput.val($('#codsinmov[i]').val());
$hiddenInput.appendTo('#tabelaeditavel');
$('#form').get(0).setAttribute('action', 'deletemoviment.php');
$('#form').submit();
});
}
});
But it doesn't work.. So, any ideas? Sorry, I'm a beginner at jQuery. Thank you very much!
you can use
$("div[id^='x['").click(function(){
// write code here })
So this will execute on click of those ids of div which start from x.
So as per my understanding You need not to use for loop here rather use 'this' keyword and do what you want.
I hope it will help you.
If you want to add an eventListener to ALL elements you can simply do it like that
var $myButtons = $('.buttons');
That way the whole list of Elements are stored behind the variable $myButtons.
Now you can proceed as following:
$myButtons.on("click", function(event){
console.log(this); // this will print out the clicked element
});
This way every element with the class .buttons is clickable and accessable.
If you want to dynamically select a single element with jquery depending on some value you have to exclude your [i] from the string
for example like that $('element:nth-child('+[i]+')');

Get elements by data attribute and part of id in jQuery

I need to get elements by data attribute and part of id in jQuery.
I have following code.
<div class="bridgeSelectedDiv" id="bridgeDiv_13234" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_13432" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_45646" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
function SelectBridgeLine(element) {
var bridgeuid = $(element).attr("data-bridgeuid");
var partofSelectedBridgeLine = $('div[id^="bridgeDiv_"]').data("bridgeuid");
console.log(partofSelectedBridgeLine);
}
But it returns only 1 element not all of them.
Any clue? Thank you!
From the docs of .data()
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
So whats happening here is it gets the data value for first element only. You need to iterate over them using .each() to get for all elements in matched selector:
$('div[id^="bridgeDiv_"]').each(function(){
console.log($(this).data('bridgeuid'))
});
Demo
It returns only 1 element because you are doing onclick="SelectBridgeLine(this);", and this will always point to current element on which the click handler exists, instead do:
$('.bridgeSelectedDiv').click(function(){
console.log($(this).data('bridgeuid')); //you can use .data()
});
or
$('div[id^="bridgeDiv_"]').click(function() {
console.log($(this).data('bridgeuid'));
});
Try
$('div[id^="bridgeDiv_"]').each(function(){
console.log($(this).data("bridgeuid")); });

How to execute partial find on dynamic HTML5 data descriptor?

I have a series of images tagged with HTML5 data descriptor "data-type2=[x]" where x is a number of different elements.
e.g.
<img data-type2="pants" class="element" src="#>
I am trying to pass that data field into a jquery function that finds classes in another div (<div class="outfit-list") that has child divs tagged with classes such as:
<div class="pants-001">
<div class="pants-002">
<div class="shoes-001">
etc.
Here is where I am stumped: how do I write a jquery function that accesses data type2 from the item I click (e.g. data-type2="pants"), finds all other divs under .outfit-list with classes that have, for example, "pants" in their class name "pants-002", and hide them? The function I have below does not work - I suspect that's because it's looking for the full name and not partial.
How do I make it perform a partial search to locate the classes that contain the term from data-type2?
<script type="text/javascript">
$(document).ready(function(){
$('.thumbslist .element').click(function(){
$('.outfit-list').find('.'+$(this).data('type2')).hide();
});
});
</script>
You can use the attribute contains selector, [attribute*="value"].
$('.outfit-list').find('[class*="' + $(this).data('type2') + '"]').hide();
You can use the starts with selector. Something like
$(".thumbslist .element").click(function() {
var type2 = $(this).data("type2");
$(".outfit-list").find("div[class^=" + type2 + "]").hide();
});
This plugin adds support for data selectors: http://plugins.jquery.com/project/dataSelector
First of all, the jQuery .data() method is amazing: http://api.jquery.com/data/
You could do:
$("#img1").data('type', 'pants')
// Or whatever else you need to attach data to. You can do this dynamically too!
t = $("#img1").data('type')
// Recall that data at some point
$("div").each(function() {
pat = new RegExp(t)
if ($(this).attr('class').search(pat) !== -1) {
$(this).hide()
}
});
Or even better in Coffeescript
t = $("#img1").data 'type'
$("div").each ->
if ($(#).attr('class').search new RegExp t) isnt -1 then $(#).hide()
May be with something like in this other question
jQuery selector regular expressions
You could just grab the value of the attribute then use it in an attribute selector: http://jsfiddle.net/n73fC/1/

How can I assign click function to many buttons using JQuery?

I have 29 buttons: todayResultsbutton0 .. todayResultsbutton28,
and 29 divs: todayResultsUrls0 .. todayResultsUrls28.
I also have a function toggleVisibility(divName) that hide/show the given div.
I am trying to use the following code:
for (var i=0; i < 29; ++i) {
var b = "#todayResultsbutton"+i;
var d = "todayResultsUrls"+i;
$(b).click(function(){toggleVisibility(d);});
}
I thought that this will cause each button click to show/hide the matching div but the actual result is that clicking on any button (0 .. 28) show/hide the last div - todayResultsUrls28.
Can someone tell me where am I wrong?
Thanks.
Use a class.
$(".myClass").click(function() {
var d = $(this).attr("id").replace("button", "Urls");
toggleVisibility(d);
});
Instead of trying to use a loop, you'd be better off using the selector to "find" your divs..
say you have something like:
<table>
<tr><td>
<input type="button" id="myButton" value="test" text="test" />
</td><td><div id="myDiv"></div></td></tr></table>
You can find myDiv by :
$('#myButton').parent().find('#myDiv').hide();
You could use the "startsWith" attribute selector with the id, then build the url from the id of the clicked item.
$('[id^=todayResultsbutton]').click( function() {
var url = this.id.replace(/button/,'Urls');
toggleVisibility(url);
});
Use
var d = "#todayResultsUrls"+i;
Instead of
var d = "todayResultsUrls"+i;
You can use this:
$('button[id^="todayResultsbutton"]').click(function() {
var index = this.id.substring(18,this.id.length);
toggleVisibility("todayResultsUrls"+index);
});
This will find all <button> tags with id's starting with todayResultsbutton. It will then get the ID for the clicked tag, remove the todayResultsbutton part of it to get the id and then call the toggleVisibilty() function.
Example here.
Edit
Notes:
Using button before the starts with selector ([id^="todayResultsbutton"]) speeds up the jQuery selector because it can use the native getElementsByTagName function to get all button tags and then only check those for the specific ID.
this.id is used instead of jQuery's $(this).attr('id') because it's faster (doesn't require wrapping this or calling the extra function attr()) and shouldn't cause any cross-browser issues.
Toggle visibility by finding the relevent div usint the event target rather than classes etc.
Assuming:
<div id='todayResultsUrls1'>
<button id='todayResultsbutton'></button>
</div>
Using the event target you can get the button element and find the div you want to hide.
var parentDiv = $(e.target).parent();
toggleVisibility(parentDiv);

Categories