I have two images on my html page and I have one button named MOVE to move them left separately. To move them I have a Jquery function with selected class.
I have two input fields each of them belongs to the particular image. My button has a click counter function so I need to get a count by clicking on the same button to both images separately into those two input fields.
I think when I select image 1, It's also should be selected input 1, and then the counter will count image 1's counts of moves and when I select image 2, It's also should be selected input 2, and then the counter will count image 2's counts of moves.
I don't know how to select multiple elements by clicking on one element. please help
My Jquery function
$(document).ready(function() {
$(".plan1").click(function() { //medium move
// unselect others
$(".plan1").removeClass("selected");
// reselect this one
$(this).addClass("selected");
});
$("#b1").click(function() {
// animate selected
$(".plan1.selected").animate({left:'+=20px'});
$('#f1.selected').val(function(i, val) { return +val+1 });
});
});
HTML
<img src="imagesource" class="plan1" />
<img src="imagesource" class="plan1" />
<input type="text" id="f1" />
<input type="text" id="f2" />
<button id="b1">MOVE</button>
This might get you started.
jsFiddle Demo
$('#f1, #f2').val('0');
$(".plan1").click(function() {
$(".plan1").removeClass("selected");
$(this).addClass("selected");
});
$("#b1").click(function() {
if ( $(".plan1.selected").length == 0 ) {
alert("Pick a pic");
return false;
}
var inpID = $(".plan1.selected").attr('id').slice(-1);
var cnt = $('#f'+inpID).val();
cnt++;
$('#f'+inpID).val(cnt);
$(".plan1.selected, #f"+inpID).animate({'left' : '+=50px' });
$(".plan1.selected").removeClass("selected");
});
* {position:relative;} /* Critical! Allows elements to move */
img, input{display:block;max-width:80px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="pic1" src="http://lorempixel.com/80/80" class="plan1" />
<img id="pic2" src="http://lorempixel.com/80/80/animals" class="plan1" />
<input type="text" id="f1" />
<input type="text" id="f2" />
<button id="b1">MOVE</button>
Notes:
(1) In CSS, you must first make the elements position:relative because the default (position:static) cannot be styled with left or right
(2) In CSS, also must make the inline elements img and input into block elements, because inline elements cannot be animated left/right
Related
I have a list of of checkboxes that are being used a search fields for a database. When someone clicks a checkbox it will show a button with the text from the label of that checkbox. However, I need that button to be have empty text when it is not visible (in the case of someone clicking the checkbox to hide the button).
Here's my code:
$(document).ready(function() {
$('#locationAll').click(function() {
var value = $('#locationAll').parent().text();
$('#location-all-button').html(value + " ×").toggle('fast');
});
});
$(document).ready(function() {
$('.search-popup').click(function() {
$(this).hide('fast');
});
if ($('.search-popup').css('display') == 'none') {
$(this).text("");
};
});
button {
background-color: lightgray;
border-radius: 20px;
display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" value="all" id="locationAll" />All
</label>
<br>
<br>
<button class="search-popup btn" id="location-all-button"></button>
For some reason I can't make the button stay hidden before the checkbox on the example here but that isn't a problem in my full code. if you need more info let me know I might have missed something.
Ok so I changed a few things. I made this work for any checkbox that follows the naming scheme I made really quickly. The scheme is the id of the button = the "button-"+id. Also I hiding all buttons with a class right form the start to set their default state.
$(document).ready(function()
{
\\change to allow all checkboxes to trigger
$('input[type=checkbox]').click(function()
{
\\change the id so it match a button when add "button-" to the start
\\this allows me to target the matching button with any chechbox
$('#button-'+$(this).attr('id')).toggle('fast');
});
$('.search-popup').click(function()
{
$(this).hide('fast');
\\ sets the check box to false so it not checked when you close it
$("#"+$(this).text().replace(" ×","")).attr('checked', false);
});
\\hides all buttons right form the start
$('button.search-popup').each(function()
{
$(this).hide();
});
});
<label>
<input type="checkbox" value="all" id="All" />All
</label>
<br>
<br>
<button class="search-popup btn" id="button-All">All ×</button>
now if you want to create and remove buttons when a checkbox has changed state you can add an if state meant in that checks to see if the button with the matching id exists or not,!$(tag).size().
I wrote the following code for an example of standard checkboxes vs. ARIA checkboxes and included the CSS and JS in one file so it can be copied/pasted. I haven't written JS in a while and I got the function I want working by calling an element by its id. I have multiple elements and I'd like to update the function to work for each one. I know it's super easy but, as I said, I haven't written JS in some time. I have the following checkboxes written by including ARIA attributes to span elements.
<fieldset>
<legend id="check_title">ARIA Checkboxes</legend>
<p>Checkboxes using ARIA and JavaScript:</p>
<div role="application">
<div class="checkboxes" aria-labelledby="check_title">
<!-- The "aria-labelledby" attribute is required because label elements can only be applied to form elements. -->
<!-- We are using span elements instead of default HTML checkbox inputs so aria-labelledby is needed for association. -->
<span role="checkbox" tabindex="0" aria-checked="false" aria-labelledby="labelA" id="optionA" onclick="toggleState();" onkeyup="ARIA_Checkbox_Key(event);">
<img src="unchecked.png" alt="" role="presentation" id="imageA">
<label id="labelA">Option A</label>
</span>
<br />
<span role="checkbox" tabindex="0" aria-checked="false" aria-labelledby="labelB" id="optionB" onclick="toggleState();" onkeyup="ARIA_Checkbox_Key(event);">
<img src="unchecked.png" alt="" role="presentation" id="imageB">
<label id="labelB">Option B</label>
</span>
</div>
</div>
</fieldset>
Then I have the following JavaScript to toggle the aria-checked attribute and the image from unchecked to checked:
<script type="text/javascript">
// This function binds the event keycode 32 (space bar) to run the function toggleState
// This is needed since the default functionality of a check box is triggered with the space bar
function ARIA_Checkbox_Key(event) {
if(event.keyCode == 32) {
toggleState()
}
}
// This function gets the aria-checked attribute of an element. If it is false, it makes it true and vice versa.
function toggleState() {
var getvalue=document.getElementById("optionA").getAttribute("aria-checked");
if (getvalue=="false") {
document.getElementById("optionA").setAttribute("aria-checked", "true");
document.getElementById("imageA").setAttribute("src", "checked.png");
} else {
document.getElementById("optionA").setAttribute("aria-checked", "false");
document.getElementById("imageA").setAttribute("src", "unchecked.png");
}
}
</script>
Clicking the image or label for Option A or Option B will toggle the class and image for Option A. This code currently works but what I can't remember and for the life of me can't figure out what to google is how to update this to account for each individual checkbox. I believe I need to create an array then reference the right point in the array but I don't recall how to accomplish that.
You need to pass through the target to the functions:
onclick="toggleState(this);"
onkeyup="ARIA_Checkbox_Key(event);"
Then for the event, use the event target:
function ARIA_Checkbox_Key(event) {
if (event.keyCode == 32) {
toggleState(event.target);
}
}
And once the target element is passed through you can get the child using getElementsByTagName:
function toggleState(el) {
var img = el.getElementsByTagName('img')[0],
getvalue = el.getAttribute("aria-checked");
if (getvalue == "false") {
console.log('toggleState', true);
el.setAttribute("aria-checked", "true");
img.setAttribute("src", "checked.png");
} else {
console.log('toggleState', false);
el.setAttribute("aria-checked", "false");
img.setAttribute("src", "unchecked.png");
}
}
I'm making an ingredients application where users insert ingredients
My application looks like this:
As you can see, the first ingredients span doesn't have a X at the end, because you must have at least one ingredient, but the rest of the ingredient spans do. I'm also using the Jquery Sortable Plugin so if you click near the outside of any of the ingredient spans, you can change the order of the ingredients. This works fine, except if you move the first ingredient span, then that span doesn't have an X at the end, even if you move it to the last spot.
So what I'm trying to do is make the first ingredient span always have no X at the end, even if switched order with another ingredient span. I tried this:
$('ingredientsCOUNT > span:first').hide(deleteButton);
but it didn't work? Any other suggestions? All help is greatly appreciated, and here's my code:
HTML (the php can just be ignored!)
<div class='formelementcontainer funky'>
<label for="ingredient">Ingredients</label>
<div id='ingredientsCOUNT' class='sortable'>
<span>
<input type="text" class='small' name="ingredient" id="ingredient" placeholder='QTY'/>
<select name='measurements'>
<option value='' name='' checked='checked'>--</option>
<?foreach ($measurements as $m):?>
<option value='<?=$m->id;?>'><?=$m->measurement;?></option>
<?endforeach;?>
</select>
<input type="text" name="ingredient" id="ingredient" placeholder='Ingredient'/>
</span>
</div>
<div class="clear"></div>
<div class='addSPAN tabover'>
<a class='float-right' id='btnAddIngredients' href='#'>Add Ingredient</a>
</div>
</div>
jQuery
(function($) {
$(document).ready(function () {
$('#btnAddIngredients').click(function () {
var num = $('#ingredientsCOUNT span').length;
var newNum = new Number(num + 1);
var deleteButton = $("<a class='float-right' style='margin:10px 2px;' href='#'><img src='<? echo base_url()."public/img/delete.png";?>' height='11' width='11' /></a>");
deleteButton.click(deleteThis);
$('#ingredientsCOUNT > span:first')
.clone()
.attr('name', 'ingredient' + newNum)
.append(deleteButton)
.appendTo('#ingredientsCOUNT')
.fadeIn();
$('ingredientsCOUNT > span:first').hide(deleteButton); //THIS IS MY SOLUTION THAT DIDN'T WORK
});
function deleteThis() {
var span = $(this).closest('span')
span.fadeOut('slow', function() { span.remove(); });
}
$( ".sortable" ).sortable(); //jQuery Sortable initialized
});
})(jQuery);
How about hiding it with CSS? The following assumes you added a class delete-button to your delete links:
#ingredientsCOUNT > span:first-child .delete-button { display: none; }
With that CSS, you can reorder the list, add or remove items, and the first delete button will never show.
Since :first-child is quirky in oldIE ( https://developer.mozilla.org/en-US/docs/CSS/:first-child#Internet_Explorer_notes ), it's possible to use the Sortable API like this:
$(".sortable").sortable({
update: function (event, ui) {
var rows = $("#ingredientsCOUNT").children("span");
rows.removeClass("first-child");
rows.first().addClass("first-child");
}
});
(there's probably a better way to utilize the event and/or ui parameters)
This way, you wouldn't have to determine which row to add a delete button to; you would always include a delete button in every row in your HTML. Then, when a sorting is done, the jQuery in the stop event (EDIT: update event) will hide the first row's delete button and show the rest (via classes).
Of course, you would need this CSS:
#ingredientsCOUNT > span.first-child a.delete-button {
display: none;
}
And to add a delete-button class to your delete buttons <a>
EDIT:
I changed the Sortable method from stop to update so that it only runs the code when the sorting arrangement has actually changed, after the sorting is done.
I want to place a number of images inside a form and be able to select them by just clicking on them. Once an image is selected I can show a border around it indicating that it has been selected, like checkboxes multiple images can be selected in the same form.
But how to go about this? I am not sure how to have the form register the images as being selected elements, so when the form is submitted to the server side the values on these images will be sent over as well.
I wish I could just set the images as backgrounds of checkboxes but of course that won't work due to browser restrictions. Any ideas on how this could be done?
for your html do have this.
<form id="form1">
<img src="barney.jpg" title="barney" id="barneyCheckImage" />
<input type="checkbox" id="imgCheck" name="imgCheck" value="barney" style="visibility: hidden;" />
<input type="submit" value="Submit" />
</form>
for your scripts
$(document).ready(function() {
$('form#form1').find('img#barneyCheckImage').toggle(
function(){
$(this).css('border', '1px solid green');
$('form#form1').find('input[id=imgCheck]').attr('checked', 'checked');
},
function(){
$(this).css('border', 'none');
$('form#form1').find('input[id=imgCheck]').removeAttr('checked');
}
);
// just to test for the checkbox.
$('form#form1').submit(function(e){
e.preventDefault();
var form = $('form#form1').serialize();
alert(form);
});
});
Edit:
I've edited it for BalusC's concern.
For the input type image you can also do a $('#imgCheck') directly instead of $('form#form1').find('input[id=imgCheck]') but for me, I don't want to have a lot of id's on my form.
check out: http://api.jquery.com/image-selector/
<input type="image" />
$("input:image").css({background:"yellow", border:"3px red solid"});
<!-- Choose some styles for our custom form elements -->
<style>
.imageCheckbox {
display: none;
}
.imageToggle .toggleImage {
/* default/unselected image styles here */
}
.imageToggle .selectedImage {
/* selected image styles here */
}
</style>
<!-- Add a script to handle when the user clicks on an image -->
<script>
function toggleImage(containerElem) {
//toggle the checkbox value
var checkBox = containerElem.getElementsByClassName("imageCheckbox");
checkBox.checked = ! checkBox.checked;
//update the image styles
var image = containerElem.getElementsByClassName("toggleImage");
if (checkBox.checked) {
image.className += " selectedImage";
}
else {
image.className = "toggleImage";
}
}
</script>
<!-- Build the form -->
<form>
<div class="imageToggle" onclick="toggleImage(this);">
<input class="imageCheckbox" type="checkbox" id="checkbox_0" name="checkbox_0" />
<img class="toggleImage" src="/img_0.png" />
</div>
<div class="imageToggle" onclick="toggleImage(this);">
<input class="imageCheckbox" type="checkbox" id="checkbox_1" name="checkbox_1" />
<img class="toggleImage" src="/img_1.png" />
</div>
<!-- etc. -->
</form>
I wanted to have some radio buttons that disabled when the mouse went over and enabled again when it went out (just for fun).
<form>
<input type="radio" name="rigged" onMouseOver="this.disabled=true" onMouseOut="this.disabled=false">
</form>
When the mouse goes on it it does what it should be when it goes back off the button wont re-enable. Also, how do I make it default to enable so that when you refresh the page it doesn't stay disabled.
Thanks in advance.
You could achieve the same effect by wrapping your radio buttons in a div tag and setting the onmouseover and onmouseout events.
<div id="container" onmouseout="this.disabled=false" onmouseover="this.disabled=true">
<input name="rigged" type="radio">
</div>
The above solution only works in IE, for a solution that works in FireFox do the following.
<script type="text/javascript">
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){
}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
*This javaScript function was borrowed from here: Enable or disable DIV tag and its inner controls using Javascript
<div id="container" onmouseover="toggleDisabled(this)" onmouseout="toggleDisabled(this)">
<input name="rigged" type="radio">
</div>
The inputs do not fire the mouseout events because they are disabled.
So you have to wrap it in a div and catch the div's events.
If you want pure javascript, use Phaedrus's example "toggleDisabled" script.
If you want jQuery and not-so-newbie friendly:
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
function toggleDisabled(d) {
var disable = d;
this.disableChildren = function() { $(this).children().each(function() { this.disabled = d; }); }
}
$("form .radios").hover(new toggleDisabled(true).disableChildren, new toggleDisabled(false).disableChildren);
});
</script>
</head>
<body>
<form>
<div class="radios">
<input type="radio" name="rigged" value="1"/> Item One<br />
<input type="radio" name="rigged" value="2"/> Item Two<br />
<input type="radio" name="rigged" value="3"/> Item Three<br />
<input type="radio" name="rigged" value="4"/> Item Four
</div>
</form>
</body>
</html>
I had a similar problem with wanting an image to expose, and then go regular when the mouse left the image. I was using jQuery and ended up hooking into mouseenter and mouseout, instead of the events you are using. You might want to try those.
$('#rigged').mouseenter(function() {
$(this).disabled = true;
}).mouseout(function() {
$(this).disabled = false;
});
Something like that.
Again, that's using jQuery.
(You'll have to give the input radio button the id 'rigged')
I think when it's becoming disabled, it's not going to fire any events.
You could try a few things.
On mouseover, make an invisible div overlay the radio box. This will make it impossible to use. Then on the mouseout of this invisible div, remove the div.
You could play with mouse x and y coords, and see if they overlay your radio elements. This isn't an optimal solution though.
Markup for the first, in jQuery, would go something like this
$('#rigged').after('<div id="overlay" style="display: none;"></div>'); // make this the size of the radio button and/or associated label (if present). also, maybe with absolute and relative positioning, make sure it will overlap the radio element
$('#rigged').bind('mouseover', function() {
$('#overlay').show();
});
$('#overlay').live('mouseout', function() {
$(this).hide();
});
You'll need to adapt this to work with multiple elements.