Priyanka Shaju
Priyanka Shaju

Reputation: 799

How to select dynamic div in onclick function

This will print number of div in a table.

    <table>
<c:forEach var="events" items="${map.theme}">
<tr><td><div id="new" class="cls" style="width: 100px;height: 100px;background-color:red;" onclick="changedropdown('${events.themeid}');">You have selected <strong>red option</strong> so i am here</div></td>
</tr>
</c:forEach>
</table>

Then this also print the same result in dropdown list

<div class="sel">
   <select class="form-control" id="theameselect">

<c:forEach var="events" items="${map.theme}">
      <option value="${events.themeid}">${events.themename}</option>

</c:forEach>
</select>
</div> 

When I click on the div then the corresponding option will set as selected in dropdown list, by using this function.And I try to change the css for the selected div.

 <script type="text/javascript">
 function changedropdown(themeid){
//set selected div values as selected in dropdown.Working well
var v=themeid;
$("div.sel select").val(v);
//it is not working well.
     $('.cls').addClass('v');
     $('.v').css("border", "14px double green");
     $('.cls').removeClass('v');

    }
</script>

But It change all the div css. 1) I need to change the css for the selected div in this function.

Upvotes: 0

Views: 1802

Answers (3)

Priyanka Shaju
Priyanka Shaju

Reputation: 799

I pass one parameter to the function as mention above answer.

onclick="changedropdown('${events.themeid}',this);"

Also use this to select the div

$(element).css("border", "14px double green"); 

Then to get one div as selected at a time, remove the class name first and add the css then add class name as previous.The script below.

function changedropdown(themeid,element){
$(element).css("border", "14px double green");
    $(element).removeClass('cls');
     var v=themeid;
     $("div.sel select").val(v);
     $(".cls").css("border", "0");
     $(element).addClass('cls');
}

And thank you for all....

Upvotes: 0

talkhabi
talkhabi

Reputation: 2759

HTML

 <div themeid="'${events.themeid}'" id="new" class="cls" style="width: 100px;height: 100px;background-color:red;" onclick="changedropdown('${events.themeid}');">You have selected <strong>red option</strong> so i am here</div>

JS

$('.cls[themeid="'+v+'"]').addClass('v');
...

example : http://jsfiddle.net/3h11vqkq/

Upvotes: 1

erkan demir
erkan demir

Reputation: 1416

Yes because changedropdown function bind for all divs. You have to pass each element to function with $(this)

<div id="new" class="cls" style="width: 100px;height: 100px;background-color:red;" onclick="changedropdown($(this),'${events.themeid}');">You have selected <strong>red option</strong> so i am here</div>

now you have selected element in fuction.. you can change things on selected element. Here is a example :

function changedropdown(selectedElement, themeid)
{
   selectedElement.css("color","red");
}

Upvotes: 1

Related Questions