0

I have a simple Javascript function, but its not working inside a form. It looks like this:

echo "<tr><td><form name='formfolder' method='POST' action='?module=pindah_dok_index' >";
echo "<input type=hidden name='id_debt' value='$_GET[id_debt]' />";
echo "move docs</td><td>";
echo "<input type='text' name='index1_dok' id='xcvbn' onkeyup='xcvbn()' style='width:80px;' required />";

But when I place my input #xcvbn before / outside the form, it works perfectly.

My Javascript function is simple like this:

function xcvbn(){    
  var xx=document.getElementById("xcvbn");
  var x = xx.value;
  var str = x.replace(/[^0-9a-zA-Z\-_.]/g, ''); 
  var str = str.toUpperCase();
  xx.value = str;
}
Zenoo
  • 12,670
  • 4
  • 45
  • 69
topansaja
  • 11
  • 2

1 Answers1

2

Your input element's id is same as the function name.

Some browsers directly accept the form element's id in JS. See the below snippet (tested in FF).

console.log(asdf.value);
<form>
<input id="asdf" value="text" />
</form>

So it makes a conflict. That's why function was not triggered. use different name for input elements id and function.

Better you can pass this object in the function argument like below.

function xcvbn(elem) {
  var x = elem.value;
  var str = x.replace(/[^0-9a-zA-Z\-_.]/g, '');
  var str = str.toUpperCase();
  elem.value = str;
}
<tr>
  <td>
    <form name='formfolder' method='POST' action='?module=pindah_dok_index'>
      <input type=hidden name='id_debt' value='$_GET[id_debt]' />move docs</td>
  <td>
    <input type='text' name='index1_dok' id='elemId' onkeyup='xcvbn(this)' style='width:80px;' required />
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • 1
    I doubt that's the issue. That would be a real problem - if the function names would be mixed with the DOM ids – Adelin Feb 07 '18 at 07:02
  • 1
    But you are right. Didn't know there's a conflict between the two. +1 – Adelin Feb 07 '18 at 07:04
  • 1
    If anyone else is curious: [Why JS function name conflicts with element ID?](https://stackoverflow.com/questions/9158238/why-js-function-name-conflicts-with-element-id) – Adelin Feb 07 '18 at 07:05
  • @Adelin Some browsers directly accept the form element's id in JS. So it makes conflicts. I would add this info in my post. – Sankar Feb 07 '18 at 07:07
  • 1
    wow its workkkk. thank you so much mr @sankar, really appreciate that. thanks everyone. thanks from me newbie :D – topansaja Feb 07 '18 at 07:50