Mani Ratna Mani Ratna - 7 months ago 13
Javascript Question

display data in text box on selection using js

I have multiple boxes. On selection of anybox I have to display its value in textbox.
Suppose I select box 1. I have to display value in textbox, and when I unselect the value must disappear. If I select multiple boxes, values must be displayed in text box separated by comma.

How can it be done?

My code is:

<input type="text" id="selectedvalue" disabled="true" class="text" name="selectedvalue" />

<tr>
<td>
<div class="box A1" id="A1"></div>
</td>
<td>
<div class="box A2"></div>
</td>
<td>
<div class="box A3"></div>
</td>
<td>
<div class="box A4 "></div>
</td>

</tr>

Answer

This can be easily done using JQuery,

Here is the JavaScript code for that

var clickedBoxes=[];

$(".box").on("click", function() {
  var clikedElem = $(this);
  var text='';

  if(clikedElem.hasClass('clicked')){
    clikedElem.removeClass('clicked');
    clickedBoxes.splice(clickedBoxes.indexOf(clikedElem.text()),1);
  }
  else{
    clikedElem.addClass('clicked');
    clickedBoxes.push(clikedElem.text());    
  }
  $('#selectedvalue').val(clickedBoxes);
});

Here is a complete JsFiddle example

Comments