AXAI AXAI - 1 year ago 83
Javascript Question

Change and Add value into array then show it



$('.inp').click(function(){
var arr = [];
var id = $(this).attr('id');
var value = $(this).val();

if(value == 'empty') {
$(this).val(id+'ON');
arr.push(value);
}
if(value == id+'ON') {
arr.splice(arr.indexOf(value), 1);
$(this).val(id+'OFF');
arr.push(value);
}
if(value == id+'OFF') {
$(this).val('empty');
arr.splice(arr.indexOf(value), 1);
}
$('.txt').val(arr.join(','));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class='txt' type='input'>
<input class='inp' id='x' type='button' value='empty'>
<input class='inp' id='y' type='button' value='empty'>
<input class='inp' id='z' type='button' value='empty'>
</form>





In my script here, I'm trying to make the
.txt
to obtain the values
ON, OFF
only, But in the part

if(value == 'empty') {
$(this).val(id+'ON');
arr.push(value);
}


the
.txt
pushes
empty
instead of the new value
id+ON


Also when i click on another button, the entire
.txt
is removed and adds the clicked button value only,

For example if i clicked
#x
the
.txt
should be
xON
, And if i clicked
#y
while
.txt
has the value
xON


i want it to be
xON,yON
but it becomes
yON
only.

Answer Source

For every button click, var arr = [];, This statement is creating an empty array for you. This should be populated from existing text field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download