Jquery on click hide the next added element - javascript

I have a button, which on every click gives the dropdown element.
Now i need to add the check box above the dropdown - which i have done, but this checkbox element should appear only for the first time.
The problem is , on every click, i get both dropdown associated with checkbox like below.
I need checkbox only for the 1st time button click- along with dropdown.
SO for the 2nd time button click, i tried to hide the checkbox, but the previous checkbox is getting hidden.
public function getPreferenceKeysAction() {
....
<div style="margin:2px 0px 15px 0px;">
<input id = "mydd" type="checkbox" name="vehicle1" value="RegisteredUsers"> Registered Users</input><br>
<input id = "mydd" type="checkbox" name="vehicle1" value="RegisteredUsers"> Opted Users</input><br>
}
in JS
$(add_button).click(function(e){ //on add input button click
if($("#mydd").length){
alert("The element you're testing is present.");
$("#mydd").hide();
}
else{
alert("NOt present.");
}
});

Why not add a class to the element or a data attribute.
With jQuery both are easy to achive.
If you want to use a class just change data method to hasClass and addClass
just do a
$btn = $(this);
// Check if the element has data attribute used
if ( $btn.data('used') != 'true' ) {
// Add data attribute used to element
$btn.data('used', 'true')
// Do whats needed for the first time it's clicked.
} else {
// The element has been used already
}

Change you id="mydd" to class="mydd", you should use id with a unique value, doing that you can hide the elements skipping 2 of them, like this.
$('.mydd').slice(2).hide();
If you want to hide the div wrapping your checkbox, add .parent()
$('.mydd').parent().slice(1).hide();

Related

OnClick event is only getting the first dynamically created row/id

I have a table where if X has a value, display X, otherwise, add a link which when clicked will display a textbox where user can input the value. I dynamically assign IDs/classes to the link and textboxes but when I run the application, each click on any link only seems to trigger the first row. I put in alerts to show what row is being clicked and I always get the first row. Looking at the browser DOM explorer, I can see that each row has its own unique ID. How do I get each OnClick event to grab the correct corresponding ID?
C#/Razor code:
<td>
Unmapped
<input type ="submit" class="editAction hidden" value="#string.Format("tr{0}",i)" name="action:ChangeToEditSubAction" />
<input type="hidden" name="#Html.Raw("EntityMapping.EMREntityID")" value="#Html.Raw(Model.DisplayResults[i].EMREntityID)" />
<span class="#string.Format("tr{0}accountTxtBox",i) hidden">#Html.TextBoxFor(m => m.EntityMapping.AssignedHOAccountID)</span> </td>
Javascript Function
function UnmappedClick() {
//$(".accountTxtBox").removeClass("hidden");
//$(".unmapped").addClass("hidden");
//$("#btnSave").removeAttr('disabled');
//$(".editAction").click();
//$(".editAction").val(null);
alert($(".unmapped").attr('id'));
var txtBox = $(".editAction").val();
var actTextBox = "." + txtBox + "accountTxtBox";
$(actTextBox).removeClass("hidden");
alert(txtBox);
}
DOM Explorer Image
You can pass a parameter from your onclick event using the "this" keyword.
onclick="UnmappedClick(this.id)"
function UnmappedClick(id){
//now you have the specific ID
}
or if necessary pass the whole control over
onclick="UnmappedClick(this)"
you can try this
$(this).attr('id') // use this
instead of
$(".unmapped").attr('id')
This will give you the current elements id when you click
As you can see here, using $('.class') will return a list all the elements with that class. When you use $(".unmapped").attr('id') you'll always get the value of the first element in the list, that's why you always get the first row.
The same will happen with var txtBox = $(".editAction").val();. With $(actTextBox).removeClass("hidden"); you'll remove the class hidden from all the elements matched.
To get the id of an element you can use onclick="unmapped(this) or onclick="unmapped(this.id)" using the following code depending on the onclick attribute
function unmapped(element) {
var id = $(element).attr('id')
alert(id)
}
function unmapped(id) {
alert(id)
}
You can check this fiddle to see them in action.

How to show/hide a specific image based on which checkbox is clicked (clicking cbox3 should open tinypic3)

I have 10 different checkboxes, each with their unique ID - in sequential order like: cbox1, cbox2, etc.. Each checkbox has an associated "tinybox" div which contains an image, and each image has an ID also in sequential order, like tinypic1, tinypic2, etc.. I'm trying to write a jQuery script so that when a user clicks on any of the checkboxes, it will then either .show() or .hide() that associated tinypic.
For example, let's say a user clicks on the third checkbox, which has id="cbox3", the script should identify this is cbox THREE and therefore show or hide "tinypic3". Each checkbox has a unique ID, but has the same Class (called cboxes).
This jQuery script successfully uses the class to run when any cbox is clicked, but how do I get it to show/hide the associated TINYPIC instead of show/hiding the cbox itself?
<script type="text/javascript">
$(document).ready(function() {
$('.cboxes').click(function() {
if ($(this).prop('checked')) {
$(this).next().show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
$(this).next().hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
</script>
I've tried substituting $(this).next().show(); for $("[id^='tinypic']").show(); or $('input:checkbox[id^="tinypic_"]') but it won't work. I'm obviously not understanding the logic somehow.
Any help is huge! Thanks a lot :)
Here's a sample checkbox for cbox2:
<li>
<input id="cbox2" type="checkbox" name="cbox2" class="cboxes" />
<label for="cbox2">Show</label>
<div class="tinybox">
<img src="http://www.example.com/img/temp.jpg" alt="tinypic2" id="tinypic2" style="display:none;">
</div>
</li>
Here is a working code jsfiddle
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
if ($(this).prop('checked')) {
image.show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
image.hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
So first we should use change event instead of click to handle not only clicks but any changes.
Secondly we should not operate only next item but find sibling by class if html changes we don't need to change the JS code.
And at the end when we find this element we should search within it for image to show it or hide based on checkbox checked state, here we can even improve my code
here is an updated version of jsfillde
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
image.toggle($(this).prop('checked'));
});
});
JSfiddle link : http://jsfiddle.net/evjkvur1/
$(this).next() //refers to the label and not the image,
Try giving
$(this).closest("li").find("img");
This example will allow you to place the tinybox divs anywhere you want on the page, and show/hide them as appropriate.
We use a separator character (the "_") to make it easy to split-off the numeric identifier from the rest of the ID. Alternately, if you cannot refactor your ID tags, you can use the slice() method, thus:
$('input[type=checkbox]').click(function(){
var i = this.id.slice(-2).replace( /\D+/g, '');
alert(i);
});
Instead of using .show() / .hide(), which you probably know well, I used the .animate() method to change the opacity, for two reasons: (1) to demonstrate how it works, and (2) just to keep the DIVs in position (since the element isn't removed from the flow, it is only rendered invisible)
jsFiddle Demo
HTML:
CB 1: <input type="checkbox" id="cb_1" /><br>
CB 2: <input type="checkbox" id="cb_2" /><br>
<div id="tinypic_1"><img src="http://placekitten.com/50/51" /></div>
<div id="tinypic_2"><img src="http://placekitten.com/48/50" /></div>
javascript/jQuery:
$('input[type=checkbox]').click(function(){
var i = this.id.split('_')[1]; //split into array at the _ & choose 2nd element
var vis = ( $(this).prop('checked') ) ? 1 : 0; //1=checked, 0=not
$('#tinypic_'+i+' img').animate({
'opacity' : vis
},800);
});
CSS:
div{display:inline-block;margin:10px;}
img{opacity:0;}

Why radio button click event behaves differently

Example on JS FIddle.
The question is:
If the first click is on the radio button, it behaves normally; But if the first click is on span text (i.e. aaaa), it can not get the checked radio.
Please tell me why and how I can make it the same.
This code, which happens when the radio button is clicked:
var obj = $(e.target||e.srcElement).parent();
score = obj.find('input:checked').val();
Puts the parent in the obj variable, which is the containing DIV. This contains both of the radio buttons. It then finds the FIRST checked input element in that DIV, which is always the one with the 'first' value after it is checked.
You should just get the value of the item which was clicked:
score = $(e.target||e.srcElement).val();
This can be rewritten as
score = $(this).val();
Here's a working example: http://jsfiddle.net/RPSwD/10/
See new fiddle.
The problem is this line:
score = obj.find('input:checked').val();
Change it to:
score = $(this).val();
The reason for this is that you're looking for the selected item in the div but on the first click, the item has yet to become selected. Given that the event is targeted at the radio button, you can assume that radio is the selected one.
Note also that you don't need to use e.target||e.srcElement. jQuery takes care of this for you. Use $(this) instead.
Additionally, you need to set a name on the radio buttons to stop both from becoming selected. Alternatively, if having both selected is desired behaviour, use check boxes instead.
You don't need to use any of the event properties:
var score = $(this).val(); // in your '.x' click handler
$('.y').click(function(e) {
$(this).prev('.x').click();
});
just wrap your radio button inside label tag like this
<label for="radio1">
<input type=radio class="x" id="radio1" value="First"/>
<span class="y">aaaa</span>
</label>
No need for extra jquery or javascript
check the demo here

Dynamically creating input elements onclick

Hey guys so I am creating input elements within a div when I click on a specific radio button with a javascript function.
It works great but when I first load the form the input elements dont appear in the div because the radio button has not been "clicked yet" although one of the radio buttons is default checked.
Basically if its checked I want them to appear, so on body load I have to call a function that checks the radio button I want default and I have to manually display the corresponding input elements that would appear if I had clicked the radio button.
This seems like a dumb work around of what I am trying to achieve, any ideas?
<body onload="startup()">
<input type="radio" name="type" onclick="createInput()" id="testradio" value="test">test</input>
<div id="area">
</div>
</body>
function startup()
{
document.getElementById("testradio").checked = true
createInput();
}
function createInput()
{
var testinput = "<input name='options' value='testing' type='checkbox'>test<br>"
document.getElementById("area").innerHTML = testinput
}
You should set the default value and then call the event. (say onchange)
something like this:
document.getElementById('elID').onchange();
this will then let your event listener fire as if the value where changed in the ui not in code.

Jquery check and uncheck checkbox with a link

I am trying to dynamically check and uncheck a box with jquery .
The ideal situation would be that if edit project file was clicked this would show the field to upload a new image (edit_project_image) was active ie not removed via either a click again on (edit_project_image) or a click on (remove_edit_image). Also if there is a strikethough, which would me that the class remove_project_image would be added then the checkbox would also be checked.
The idea is if any of the above is true the the current active image needs to be removed.
Here is my jquery right now:
//show hide the file box to edit images
$('.edit_project_file').live('click',function() {
$(this).parent().next().toggle();
$(this).parent().removeClass("remove_project_image");
return false;
});
//allow the user to remove the file box if they don't wish to edit an image
$('.remove_edit_image').live('click',function() {
$(this).parent().hide();
$(this).parent().removeClass("remove_project_image");
return false;
});
//add strikethough when the user decides to delete an image
$('.remove_project_file').live('click',function() {
$(this).parent().toggleClass("remove_project_image");
$(this).parent().next().hide();
return false;
});
Here is the Html Markup:
<ul class="imgPreview">
<li>
manager_pimg3_7_1281126121.jpg
<img src="images/edit.gif"/>
<img src="images/delete.gif"/>
</li>
<li class="edit_project_image">
<input name="upload_project_images[]" type="file" />
<img src="images/delete.gif" />
</li>
<li>
<input name="edit_image[]" type="checkbox" value="manager_pimg3_7_1281126121.jpg" class="edit_image_checkbox"/>
</li>
</ul>
I believe the best situation would set a var that if true will set the value of the checkbox to true.
Things i've tried include:
$('.remove_project_file').live('click',function() {
$(this).parent().toggleClass("remove_project_image");
$(this).parent().next().hide();
if ($(this).parent().next(".edit_image_checkbox").is(":not(:checked)")){
$('.edit_image_checkbox').attr('checked',true);
}
return false;
});
The this works in the sense that it checks all (the above is in a php loop) the checkboxes with the class of .edit_image_checkbox instead of just the one next to the class of the remove_project_file that was clicked. Also there is no uncheck when the link is checked again for this i tried else {$('.edit_image_checkbox').attr('checked',true);} this just confuses it as it says if it's not checked then check it but then if it's checked uncheck it.
Another idea i had was to use a variable and set it to true or false and if true the box is checked. I tried this like:
var file_checkbox_checked = false;
if(file_checkbox_checked == true){
$('.edit_image_checkbox').attr('checked',true);
}
else{
$('.edit_image_checkbox').attr('checked',false);
}
Then added file_checkbox_checked = true; to each of the functions that should check the checkbox. This seemed to do nothing. I could set var file_checkbox_checked = true; and that would check all the checkboxes another problem with this is there is no way to uncheck it.
I am still in the learning, brainstorming part of this part of the project so if you have any ideas they would be great.
I understand your requirement correctly [when does programmers not :) ], when user clicks edit or remove image you add or remove remove_project_image class to the li containing edit/remove link. Now if the class remove_project_image is added to the li you want to check the checkbox otherwise clear it. The following snippet does this.
$('.remove_project_file').live('click',function() {
$(this).parent().toggleClass("remove_project_image");
//TO KNOW IF STRIKE-THROUGH IS APPLIED TO IT OR NOT
var r = $(this).parent().hasClass("remove_project_image");
$(this).parent().next().hide();
//WE NEED TO GET THE LI CONTAINING CHECK BOX, ONE NEXT TO HIDDEN ONE
var t = $(this).parent().next().next();
//GET CHECKBOX
var c=$(".edit_image_checkbox", t);
$(c).attr('checked',r);
return false;
});

Categories

Resources