Ƥŕaśađ Şŕįɱał Ƥŕaśađ Şŕįɱał - 5 months ago 12
jQuery Question

Select multiple html elements by clicking on one element in Jquery

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>

Answer

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

Comments