I just started with JavaScript and have a small question. On my website I have three div-elements:
<div id="id_1" class="class_1" onclick="itemSelected('id_1')"></div>
<div id="id_2" class="class_2" onclick="itemSelected('id_2')"></div>
<div id="id_3" class="class_3" onclick="itemSelected('id_3')"></div>
I added the following script to highlight the one that the user has clicked:
var selected = false;
function itemSelected(element) {
if (selected == false) {
document.getElementById(element).style.backgroundColor = "#f5b03d";
selected = true;
}
else {
document.getElementById(element).style.backgroundColor = "#99d4e5";
selected = false;
}
}
So far, this works and the user clicks an item and it gets highlighted in another color. If he clicks it again, it gets his default background color. But as soon as the user clicks one of the other items, it gets highlighted too. What I want is a single-choice functionality: As soon as the user clicks one item, the other too appear in their default background-color. Can someone help me with this problem?
Thanks in advance!
Add a shared class to each element.
When the user clicks an element use that shared class to set the default background color to all three elements.
Then use the element's unique ID to set the highlighted background color to the element that has been clicked.
<div id="id_1" class="class_0" onclick="itemSelected('id_1')"></div>
<div id="id_2" class="class_0" onclick="itemSelected('id_2')"></div>
<div id="id_3" class="class_0" onclick="itemSelected('id_3')"></div>
function itemSelected(element) {
$('div.class_0').css({'background-color':'#99d4e5'});
document.getElementById(element).style.backgroundColor = "#f5b03d";
}
Change the html as above and use this jquery
You can do this without using javascript, created a fiddle for this:
http://jsfiddle.net/6PUwz/
What I have done is, making the divs focusable by setting tabindex="-1" and doing the selection by the use of the css-pseudo-class :focused.
Check if this fits you requirements.
Related
I have a simple html menu, when a menu item is clicked a class of `mg_cats_selected" is added to the anchor tag (which is the menu item).
I would like to copy the text value of the active/selected anchor tag and display it in another div on the page, but I would like to only display it once. When a new item link is clicked, I want to remove the old value from the separate div that I've created it and display the new value of the new selected menu item.
I hope that makes sense.
This is the HTML menu
<div id="mgf_165" class="mg_filter mg_new_filters">
<a rel="163" id="163" class="mgf_id_163 mgf mg_cats_selected left_menu" href="javascript:void(0)">Bathrooms Sinks</a>
<a id="164" rel="164" class="mgf_id_164 mgf left_menu" href="javascript:void(0)">Bowed</a>
</div>
This is the jQuery and the div where I wanna display the text values.
<script type="text/javascript">
jQuery(document).ready(function(){
console.log('test');
jQuery("a.left_menu").click(function(){
var txt = jQuery("a.left_menu").text();
//$(this).attr('rel');
jQuery("#category").append(txt);
});
});
</script>
<div id="category">
</div>
At the moment when I click on, say, "Bowed", this displays in the div
Bathrooms SinksBowed
And if I click again on "Bathroom Sinks", the same thing repeats
Bathrooms SinksBowedBathrooms SinksBowed
How can I deal with that? And did I follow the correct logic here?
You are currently getting the text of all the menu items and then appending it to the div.
You need to get the text of the clicked menu item, and then set the content of the div to the text value of that menu item.
jQuery(this) // the clicked menu item
jQuery('#category').text('VALUE') // set the text content of the tag to VALUE
Working solution on JSFiddle..
See Inside the Event Handling Function to learn more about jQuery event handling.
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;}
I want to open a dropdown on click of a image and also display a alert message that which of the dropdown option is being clicked .
My html code is :
<div class="account_notification">
<a href="#">
<div class="notify_notification">click</div><!-- notify_notification close --></a>
</div><!-- account_notification close -->
<select class="select1" size="5" style="display:none">
<option name="test" value="" class="first">Select</option>
<option name="test" value="" class="">NOTIFICATION1</option>
<option name="test" value="" class="">NOTIFICATION2</option>
</select>
What will be javascript code to do so ?
Though i found a jquery on inernet for dropdown display but that also without showing which option is selected and also i know very little about jquery .So i want code in javascript.Please help
Jquery i found is as follow :
$('.notify_notification').click(function() {
$('.select1').toggle();
});
I got the code from answers but the problem here is suppose before click if the bar is like this:
http://postimg.org/image/n04ggm7ux/
After clicking the image the bar become :
http://postimg.org/image/4h344hl7t/
How to get it down instead of being displayed along side ?
If you want to open the dropdown, not just to unhide the select element... Well, you're in trouble, because there is no generic or simple solution for that. Consider building your custom drop-down, trying another elements (like radio buttons) or using Shadow DOM.
To show the selected option, use something like this:
alert($('.select1 option:selected').text()); //show text of selected option
alert($('.select1').val()); //show selected value
You actual code is showing/hide the select; if you want to open the select programmatically is not possible even if you trigger a click the drop down list won't open like if the user clicked on it. An alternative is to use a custom select display plugin (like chosen).
To display the select value on option click use the change event:
$('.select1').change(function(){
alert($(this).val());
alert($(this).find('option:selected').text())
});
Demo: http://jsfiddle.net/IrvinDominin/YdJzP/
If you want only JavaScript solution.
You can toggle your combo with this:
function toggle(){
var elem = document.getElementById("myselect");
if(elem.style.display == "none")
elem.style.display = "block";
else
elem.style.display = "none";
};
And after adding onchange="selectHandler(this)" to your select on html, you can get selected value with:
function selectHandler(x) {
if(x.value!="")
alert("Selected: "+x.value);
toggle();
}
Here is a only example: JSFIDDLE
I have a menu that is displayed when a user hovers over an anchor tag with a certain class. The same menu is always displayed, but the anchor tags have a different "accNum" attribute. I want to get the value of the accNum attribute from the "parent" element that displayed the menu and append it to the click event of one of the menu items. Something like;
Actions
Actions
Actions
<div id="ActionsMenu" style="display:none;">
Show Account
</div>
Whichever 'ActionLink' is the one hovered over to display the menu, i want to take that AccNum value and create the onClick event of "ShowAccountValues" something like
onClick="showAccountValues('AccNum value of parent');"
any help would be great. Also, I assume I have to bind this to the document.ready() function for 'ActionLink' which makes sense, but i figured if i could get any of it through this that would be great.
Thank you
Firstly use jQuery to hook up your events, secondly accnum isn't a valid attribute, so use a data-* attribute like this:
Actions
Actions
Actions
<div id="ActionsMenu" style="display:none;">
Show Account
</div>
Then you can update the data attribute of the #showAccountValues link on hover of each a element:
$('.actionLink').on({
click: function(e) {
e.preventDefault();
$('#ActionsMenu').show();
},
mouseover: function() {
$('#showAccountValues').data('accnum', $(this).data('accnum'));
}
});
Then on the click of the a element in #ActionsMenu you can get the accnum:
$('#showAccountValues').click(function(e) {
e.preventDefault();
showAccountValues($(this).data('accnum'));
});
Example fiddle
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;
});