0

i want set value of input type if condition is true but my function not working. i write the correct code but dont know what wrong with it.

<head>
<script type="text/javascript">
function ghg(){
  var fname= document.getElementById('jitender').value;
  if(fname=="") {
    fname= "i am value";
  }
}
</script>
</head>

<body>
  <input type="text" id="jitender" value="" />
  <input type='button' value="submit" onclick="ghg()"/>
</body>
1
  • 1
    please remove unnecessary linebreaks! Commented Jul 14, 2012 at 13:23

5 Answers 5

1
function ghg(){
  var finp= document.getElementById('jitender');

  if(finp.value == "") {
    finp.value = "i am value";
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@amit, in your function, fname is not a pointer to the field's value attribute. fname is not a pointer, it is a string
1

have you already tried this:

document.getElementById('jitender').value = "blaah"

1 Comment

because, javscript works this way. you don't get the full instance with that call, but only the value (as a string).
1
var finp= document.getElementById('jitender');
if(finp.value=="")
   finp.value= "i am value";

Comments

1

In your function, fname is not a pointer to the field's value attribute. fname is a string. So, you if you assign fname a different value, document.getElementById('jitender').value will still contain the old value.

This is how to change the input's value:

function ghg()
{
  var e = document.getElementById('jitender');
  if (e.value=='') e.value = 'i am value';
}

In this function e is a pointer to the object representing the DOM element with the id jitender. So, in this case document.getElementById('jitender') and e are pointers to the same object, thus, setting e.value will change the input's value.

Comments

1

This was touched on briefly in a comment, but the code you posted does not work because the variable fname is set BY VALUE not BY REFERENCE.

This means fname equals the value of whatever document.getElementById('jitender').value is. When you set the value of fname, because it was set BY VALUE you're setting the value of fname only, it does not have a reference to the property it "came from".

The correct solution is to do

document.getElementById('jitender').value = "whatever"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.