ikiK
ikiK

Reputation: 6532

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...

This peace of code gives me a result that php variable is inserted into a wanted filed.

Lets say the PHP variable is data1-data2:

  document.hiderad.selectstate.onchange = updateText;

function updateText() {
    var str = document.hiderad.selectstate;
    document.hiderad.opis.value = str.value;
}

Code above inserted data1-data2 into wanted HTML input.

And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?

document.hiderad.selectstate.onchange = updateText;
function updateText() {
    var str = document.hiderad.selectstate;
    var array = str.toString().split('-');
    a = array[0], b = array[1];
    document.hiderad.opis.value = a.value;
    document.hiderad.iznos.value = b.value;
}

Code above gives me b undefined if i remove last line i get a undefined.

Upvotes: 0

Views: 70

Answers (1)

Barmar
Barmar

Reputation: 780869

You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.

Also, always declare local variables unless you have a specific reason to assign global variables.

function updateText() {
    var str = document.hiderad.selectstate;
    var array = str.value.split('-');
    var a = array[0], b = array[1];
    document.hiderad.opis.value = a;
    document.hiderad.iznos.value = b;
}

Upvotes: 1

Related Questions