开发者

Using JavaScript to modify form [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have an HTML form with three fields:

  • Status
  • Department, and
  • Delivery Method

I want to display or hide the fields, depending upon whether the user's browser supports JavaScr开发者_StackOverflowipt.

I'm also trying to set one field based upon the value of the other. If status is set to DE, then I want to set the value of delivery method to DE as well.

How would I go about implementing this functionality?


Aren't fields you are using created using html tag? I'm not sure how you can use JAVA to disable them but you can surely use a simple javascript statement.

Say the status field has the id as 'fStatus'. Then you can simply do the following:

<script type="text/javascript>
document.getElementById('fStatus').type = 'hidden'; //to hide it and
document.getElementById('fStatus').type = 'text';   //to un-hide it
</script>

Now to execute to execute a function when status changes you will need to modify the html a bit. Like this:

<input type="text" id="fStatus" onChange="validate()" />

and to execute the same function when the page load, modify body as such:

<body onLoad="validate()">

The appropriate javascript function would be:

<script type="text/javascript">
function validate()
{
  if(document.getElementById('fStatus').value == "DE")
  {
    document.getElementById('fDelivery').value = "DE"; // Assuming that the id of the delivery field is 'fDelivery'
  }
}
</script>


If you want to hide the form if JS is not supported, why not hide it by default and then show it using javascript?

jQuery would make this really easy:

jQuery(function() {
  $("form#formID").show();
});

jQuery also makes it easy to check the values of form fields:

$("input#user_email").val() //=> 'user@email.com'

I'd use jQuery if you can ;)


Hide it by default with css:

#formID {
    display: none;
}

Then with js you can display it:

document.getElementById('formID').style.display = 'block';


The general idea will be to bind an onchange event listener to your "status" field:

document.getElementById("status").onchange = function() {
    var currentValue = this.value;
    document.getElementById("deliveryMethod").value = currentValue;
}

Inside that function, you get the value of the element that has changed with this.value. You can then do whatever you like with that value, such as assign it to the value of another field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜