reading from input tag outside form element

2019-03-03 21:16发布

问题:

I have a web page with an input field (a calendar to select a date from).
The problem is that I need to read that input field from 2 different form elements that each have their own action and other values.

|calendar|   [do this]   [do that]

I don't want to copy the input field in both forms since it would look silly. Any suggestions?

Edit: here's the two forms:

<form action="/adm/user/credit/update?sms=<?=$id?>&user=<?=$user?>" method="post">
    <input type="hidden" name="isPaid" value="1"/>
    <label for="datums">Datums: </label>
    <input type="text" id="datums" name="datums"/>
    <input type="submit" value="Paid" style="background-color:green; color:white"/>
</form>
<form action="/adm/user/credit/extend?sms=<?=$id?>&user=<?=$user?>" method="post">
    <input type="hidden" name="phone" value="<?=$phone?>">
    <select name="period">
        <option value="7">7</option>
        <option value="14">14</option>
        <option value="30">30</option>
    </select> days
    <input type="submit" value="Extend" style="background-color: blue; color: white">
</form>

回答1:

Just give it unique ID and use document.getElementById like this anywhere you want:

var myValue = document.getElementById("myInputID").value;

This way it doesn't matter where the input is located, it can even be outiside of any form.

Edit:
To read the value upon submit, first add the onsubmit part to the relevant form:

<form action="....." onsubmit="ReadValue(this);">

And now have this in your page:

<script type="text/javascript">
function ReadValue(oForm) {
   var myValue = document.getElementById("myInputID").value;
   alert("value is: " + myValue);
}
</script>

This will show the value as alert dialog.. if you want to populate hidden form field with the value, have such code instead:

function ReadValue(oForm) {
   var myValue = document.getElementById("myInputID").value;
   oForm.elements["myHiddenFieldId"].value = myValue;
}

Hope it's clear enough! :)