2

Im trying to delete content of some elements based on the drop down selection. I have tried this code the alert shows the new value is empty but when I save it, targeted element still has content.

Here's my code:

var res = document.getElementById("select-result").value; //alert(res); function clearValues(id, inputType) { var td = document.getElementById(id); if (td != undefined || td != null) { var res = td.getElementsByTagName(inputType)[0].value; alert(res); // returns the content of element if (res != "") { res = ""; alert("New res value: " + res); //returns empty } } } 

Note: If i manually remove content of the target element it saves it as empty. That's puzzling
for me. What's the difference shouldn't javascript make things easier rather than manually emptying fields.

5
  • show your saving part pls.. Commented Jun 2, 2014 at 3:13
  • innerText or innerHtml ti reassign the value to "" Commented Jun 2, 2014 at 3:15
  • @Sudhir, its part of the application you just call it. Commented Jun 2, 2014 at 3:16
  • Not sure if it works for your purposes but you can always use the reset() method to reset your form. Of course this will return all form elements back to their original value. Commented Jun 2, 2014 at 3:17
  • in your if condition, always res is expect to be empty. so you don't need to check value of that element. Just do res = "" in your if condition. Commented Jun 2, 2014 at 3:25

3 Answers 3

1

You're setting res to the value of the textbox - not to the value property. So you're only setting the res variable to empty, not the textbox's value. Try this, instead:

var res = document.getElementById("select-result").value; function clearValues(id, inputType) { var td = document.getElementById(id); if (td != undefined || td != null) { var res = td.getElementsByTagName(inputType)[0].value; if (res != "") { td.getElementsByTagName(inputType)[0].value = ""; } } } 
Sign up to request clarification or add additional context in comments.

Comments

1

You've assigned the value of the textarea to a new variable, res, but res is not a pointer to the value, it's basically a duplicate copy of that value and any changes made to res will not be reflected in the original value.

Consider this code:

var fruit1 = "apples" var fruit2 = fruit1; fruit2 = "oranges" alert(fruit1); // still "apples" alert(fruit2); // now "oranges" 

So, you want to change the actual value property of the original elements like so:

td.getElementsByTagName(inputType)[0].value = ""; 

Comments

0

Try this.

function clearValues(id, inputType) { var td = document.getElementById(id); if (td != undefined || td != null) { var element = td.getElementsByTagName(inputType)[0]; elmValue = element.value; if (elmValue != '') { element.value = ""; } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.