jQuery set click handler with per-element information - javascript

I have a onclick attribute ontag now that gets set serverside with the REQUIRED_ID for when the user clicks on it.
The problem now is that I am trying a more jQuery-like approach where I do set the click handlers on document ready but now I don't have the REQUIRED_ID at hand to set it.
I'm wondering what would be the jQuery way of doing this, perhaps setting another tag with the REQUIRED_ID and reading it on ready?
NOW:
$.ready(
$('select.attr_satus>option:not(:selected)').each(
/* I AM MISSING REQUIRED_ID, WHERE DO I GET THIS VVVVVV*/
$(this).click(function(){ statusChanged(this,REQUIRED_ID,$(this).val()); })
);
);
BEFORE:
<select class="attr_status">
<option onClick='statusChanged(this,REQUIRED_ID,"draft");' value='draft'>Draft</option>
<option value='publish' selected="true">Published</option>
</select>
REQUIRED_ID is an id that changes per row, as I have several of those select tags one after each other.

You can store your extra information in "data-" attributes:
<select class="attr_status">
<option data-requiredId='REQUIRED_ID' value='draft'>Draft</option>
Then in your event handler you can get it with ".data()":
$(this).click(function() {
statusChanged(this, $(this).data('requiredId'), this.value);
});
edit — Now "data-" attributes are standardized with HTML5. Another approach is to use the "class" string, which can contain pretty much anything. What I've done is use a "name:value" notation:
<select class="attr_status">
<option class='requiredId:REQUIRED_ID' value='draft'>Draft</option>
Then in the handler:
$(this).click(function() {
var id = this.className.replace(/^.*\brequiredId:(\S+).*/, '$1');
statusChanged(this, id, this.value);
});

Related

Adding onclick attribute to a dynamically created option

I have a script where I am appending options to a select item and would add the onclick method to them.
My piece of code is this:
$(obj).closest('td').next('td').find('.select').append(new Option("i", "i"));
and this is how it looks when I inspect them:
<option value="i">i</option>
but I want them to be
<option onclick="functionname" value="i">i</option>
Is there anyway to do it with jQuery? Thanks in advance
A much better idea would be to put a click event handler on the select itself, then read the value which was selected.
This is for two reasons. Firstly inline event attributes, such as onclick, are no longer good practice and should be avoided where possible. Secondly, event handlers on option elements are unreliable at best and just plain don't work at worst.
The best way to achieve what you need is to add a change event handler to the select and read the selected value from the chosen option at that point, something like this:
let $foo = $('#foo').on('change', e => {
console.log(e.target.value);
});
$('button').on('click', () => {
let ts = (new Date()).getTime();
$foo.append(`<option value="${ts}">${ts}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add option</button>
<select id="foo"></select>
I wouldn't do it for an onclick attribute since, as already stated, there are faster and better ways to reference it directly from JS. But for future reference or if you need to set other attributes, you can use the built in setAttribute. An example would be yourelement.setAttribute("class","classname").
After adding a new option, you could create a listener for that select like this:
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
jQuery('select').append(new Option('New Option', 'value'));
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

jQuery find all attr rel

I have a this select dropdown:
<select id="category">
<option value="cat1">Category 1</option>
<option value="cat2">Category 2</option>
</select>
and I have this code that everytime I select something form the dropdown it takes the value and find the same class and show it on the last line
$('#category').change(function () {
var selected_category = $(this).val();
$('#sub-category').find('.option').hide();
$('#sub-category').find('.'+selected_category).show();
});
I just want to change instead of class so it will find the attribute rel
** edited **
You definitely don't need jQuery for this. Here's the code to find all option tags with a rel attribute of "sub-cat1":
document.querySelectorAll('option[rel="sub-cat1"]')
The above will work in IE8 and up, which should satisfy all browsers you need to support. The jQuery solution is similar, and uses the same selector string:
$('option[rel="sub-cat1"]')
Furthermore, you don't need to add a class of "option". Simply select using the option tag name.
There can be an alternate way to your answer.
Using jquery try ,
$ (".classname").each(function(){
//iterate over similar *classname* elements one by one
$(this).someFunc(); //it will help you to preform operation at current value while iteration
});
With rel if you want to iterate over rel tag values , try
$("[rel='sub-cat-1']").each(function(){
//Some operation
});

Change element's ID multiple times

so what I'm triying to achieve is that I want one element to append some other elements to div and change its ID attribute (or something similar).
i have tried something like this
$('#add3').click(function(){
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
and also tried something like this:
$('#add').click(function(){
var vari = $("<div id='add2'>add another user</div>");
$('#add').remove();
$('.third_row1').append(vari);
$('.third_row1').append('something to append');
});
so clicking one button (like second example) has no effect on third, fourth ... n click
same thing with the second example
thanks in advance for help
UPD
ok, so here's how I generate selects which I want to append
<jsp:useBean id="obj1" class="com.Users" scope="page"/>
<div class="third_row1">
<select name="mySelect1" id="mySelect1">
<c:forEach var="item1" items="${obj1.items}">
<option>${item1}</option>
</c:forEach>
</select>
</div>
all I want to do is to add same select, but with different ids and names
Since elements IDs are changed dynamically, you should use delegated event handlers with .on().
For example:
$(document).on("click", "#add3", function() {
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
If all these elements (#add, #add3) are inside page static element, it will be better to use this element instead of document for perfomance:
$("static_element_selector").on("click", "#add3", function() {
And just to note: since this inside event handler points to clicked DOM element, you can use this.id = "add4" instead of $('#add3').attr("id", "add4");. It is shorter and works slightly faster.

How to clone elements and generate dynamic ids

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

How Can I Interact With <option>

Lets say I have
<select>
<option value="longSleeve">Long Sleeve</option>
<option value="shortSleeve">Short Sleeve</option>
</select>
how can I make my code do something when one is pressed.
For example how can I make a variable set to 1 when 'Long Sleeve' is chosen and set the variable to 2 when 'Short Sleeve' is chosen and then if 'Long Sleeve' is chosen again set it back to 1.
Also pardon my noobyness at coding
What you are looking for is the onchange event handler, in jQuery you can use .change() or .on('change', handler) like this:
var someVariable;
$('select').on('change', function(){
someVariable = this.selectedIndex + 1;
});
with jquery you can always add listeners like
.click()
to any tag on your html code, maybe you can add an id to that tag
<option id="firstOption" value="longSleeve">Long Sleeve</option>
and have something like
$("#firstOption").click(function(){
alert("click First option!");
});
hope this help : )
link to jquery reference...

Categories

Resources