Finding `datalist` by Name in Form? - javascript

Given a form:
console.log(document.getElementById('f').elements['a']);
console.log(document.getElementById('f').elements['b']);
<form id='f'>
<input name='b' list='list' type='text'/>
<datalist name='a' id='list' />
<input name='btn' type='button' value='go'/>
</form>
Why does my attempt to get the datalist by name a return undefined? However, when I search by name b, it succeeds?

According to https://www.w3.org/TR/html5/infrastructure.html#htmlformcontrolscollection-0 elements that can be in elements property are:
button, fieldset, input, keygen, object, output, select, textarea
So, if you want <datalist> to be considered as element - you can refer to W3C)

You can use .children. The control for the element would be <input> element having attribute list="list", at <form> submission the key, value pair would be name b, value selected <option> child element of <datalist> element, select an <option> submit <form> and see Network tab for resulting query string parameters
b:123
btn:go
or
b:456
btn:go
Note <datalist> element is not self closing, closing </datalist> tag is required for valid HTML.
onload = () => {
console.log(document.getElementById('f').children["a"]);
console.log(document.getElementById('f').elements['b']);
}
<form id='f'>
<input name='b' list='list' type='text' />
<datalist name='a' id='list'>
<option value="123">123</option>
<option value="456">456</option>
</datalist>
<input name='btn' type='submit' value='go' />
</form>

The elementsproperty only contains form controls. Since datalist is not a form control, it is not included. For more information see MDN docs on HTMLFormElement and the associated collection.

Related

Value from a dynamic JS computed value returns NULL when php gets the input value [duplicate]

I have some disabled inputs in a form and I want to send them to a server, but Chrome excludes them from the request.
Is there any workaround for this without adding a hidden field?
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
</form>
Elements with the disabled attribute are not submitted or you can say their values are not posted (see the second bullet point under Step 3 in the HTML 5 spec for building the form data set).
I.e.,
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
FYI, per 17.12.1 in the HTML 4 spec:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successfully posted.
You can use readonly attribute in your case, by doing this you will be able to post your field's data.
I.e.,
<input type="textbox" name="Percentage" value="100" readonly="readonly" />
FYI, per 17.12.2 in the HTML 4 spec:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements are successfully posted.
Using Jquery and sending the data with ajax, you can solve your problem:
<script>
$('#form_id').submit(function() {
$("#input_disabled_id").prop('disabled', false);
//Rest of code
})
</script>
To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.
<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
<!-- Re-enable all input elements on submit so they are all posted,
even if currently disabled. -->
<!-- form content with input elements -->
</form>
If you prefer jQuery:
<form onsubmit="$(this).find('input').prop('disabled', false)">
<!-- Re-enable all input elements on submit so they are all posted,
even if currently disabled. -->
<!-- form content with input elements -->
</form>
For ASP.NET MVC C# Razor, you add the submit handler like this:
using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
// Re-enable all input elements on submit so they are all posted, even if currently disabled.
new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
<!-- form content with input elements -->
}
If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.
I'm updating this answer since is very useful. Just add readonly to the input.
So the form will be:
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<input type="textbox" name="Percentage" value="100" readonly/>
</form>
Semantically this feels like the correct behaviour
I'd be asking myself "Why do I need to submit this value?"
If you have a disabled input on a form, then presumably you do not want the user changing the value directly
Any value that is displayed in a disabled input should either be
output from a value on the server that produced the form, or
if the form is dynamic, be calculable from the other inputs on the form
Assuming that the server processing the form is the same as the server serving it, all the information to reproduce the values of the disabled inputs should be available at processing
In fact, to preserve data integrity - even if the value of the disabled input was sent to the processing server, you should really be validating it. This validation would require the same level of information as you would need to reproduce the values anyway!
I'd almost argue that read-only inputs shouldn't be sent in the request either
Happy to be corrected, but all the use cases I can think of where read-only/disabled inputs need to be submitted are really just styling issues in disguise
I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.
<input readonly style="color: Grey; opacity: 1; ">
Simple workaround - just use hidden field as placeholder for select, checkbox and radio.
From this code to -
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
<select name="gender" disabled="disabled">
<option value="male">Male</option>
<option value="female" selected>Female</option>
</select>
</form>
that code -
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<input type="textbox" value="100" readonly />
<input type="hidden" name="gender" value="female" />
<select name="gender" disabled="disabled">
<option value="male">Male</option>
<option value="female" selected>Female</option>
</select>
</form>
In addition to Tom Blodget's response, you may simply add #HtmlBeginForm as the form action, like this:
<form id="form" method="post" action="#Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"
Define Colors With RGBA Values
Add the Following code under style
<!DOCTYPE html>
<html>
<head>
<style>
#p7 {background-color:rgba(215,215,215,1);}
</style>
</head>
<body>
Disabled Grey none tranparent
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input id="p7" type="textbox" name="Percentage" value="100" readonly="readonly"" />
</form>
result
I had exactly the same problem, but did not work for me, because I have select HTML element, and it's read-only state allowed to change its value.
So I used select in one condition and input in another:
<% If IsEditWizard Then %>
<%For Each item In GetCompaniesByCompanyType("ResponsibleEntity")%>
<% If item.CompanyCode.EqualsIgnoreCase(prCompany.GetAsString("LinkedCompany")) Then %>
<input type="text" value="<%: item.CompanyName %>" tabindex="3" size="12" maxlength="12" readonly="readonly" />
<input type="hidden" id="LinkedCompany" name="LinkedCompany" value="<%:item.CompanyCode %>" tabindex="3" size="12" maxlength="12" />
<%End If %>
<%Next %>
<%Else %>
<select id="LinkedCompany" name="LinkedCompany" class="w-auto" <%= If(IsEditWizard, "disabled", "") %>>
<option value="">Please Select</option>
<%For Each item In GetCompaniesByCompanyType("ResponsibleEntity")%>
<option value="<%:item.CompanyCode %>" <%: IIf(item.CompanyCode.EqualsIgnoreCase(prCompany.GetAsString("LinkedCompany")), "selected", String.Empty) %>><%: item.CompanyName %></option>
<%Next %>
</select>
<%End If %>
use
<input type="textbox" name="" value="100" disabled/>
or
<input type="textbox" name="" value="100" readonly/>
if your are using framework like PHP Laravel, element without name attribute will read as unset
<input type="textbox" value="100" disabled/>
You can totally avoid disabling, it is painful since html form format won't send anything related to <p> or some other label.
So you can instead put regular
<input text tag just before you have `/>
add this
readonly="readonly"
It wouldn't disable your text but wouldn't change by user so it work like <p> and will send value through form. Just remove border if you would like to make it more like <p> tag

Ajax form select changes doesn't appear in jQuery .serialize/.val

I'm retrieving form with .load jQuery function and places it in document body.
After that I'm changing select value (manually) and trying to save form with ajax .post request.
Select value retrieved by jQuery in any way (with .val or sereilize) doesn't changes. Value stays as it was rendered.
Without prevetnDefault (with plain POST request) form saves as expected. But both .val on select or .sereilize on form returns old select value (not really selected).
<form
id="phrase-fake-form-12243"
method="POST"
action="/phrase-fake/change-group/12243/3">
<input type='hidden' name='csrfmiddlewaretoken' value='UQuHH3ahAnBaSUPsCBaF1QKF4I0O48AO' />
<select name="group" id="phrase-fake-modal-group-dropdown">
<option value="20393"
selected="selected">
1
</option>
<option value="20405"
>
2
</option>
<option value="20417"
>
3
</option>
</select>
<input type="submit" value="Сохранить" class="ui button blue">
</form>
JS:
<script>
$("#phrase-fake-form-12243").submit(function (event) {
console.log($('#phrase-fake-form-12243').serialize())
console.log($('#phrase-fake-modal-group-dropdown').dropdown('get value'))
$.post('/phrase-fake/change-group/12243/3', $('#phrase-fake-form-12243').serialize())
event.preventDefault();
});
</script>
What I'm doing wrong? Actually it's seems like a bug..
Try using this library, form2js
You just have to call the method .toObject() on the jQuery object.
For example, if this is your html
<form id="test">
...
</form>
You can get the all the form element values by
var formObject = $("#test").toObject();

Calculate then change form field value onselect

I have a form that has some field values pre-populated from a PHP query. I am trying to change the value of the AMOUNT field by adding $2.00 to the existing value if a selection made in field "os0" contains "XX" anywhere in the selected value. I am having trouble getting the javascript code correct to make this work, i think im using the DOM wrong but not sure. The remote URL is only receiving the value set by the PHP echo on submit, regardless of the option/value selected for field "os0". Any help please.
<form method="post" action="remote-url" name="ppal">
<input type="hidden" name="amount" value="<?=$res[0]?>">
<input type="hidden" name="SKU" value="<?=$res[1]?>">
<select id="os0" name="on0" onChange="setval()">
<option value="Small">Small</option>
<option value="Medium">Medium/option>
<option value="Large">Large</option>
<option value="XL">X-Large</option>
<option value="XXL">XXL</option>
<option value="XXXL">XXXL</option>
<input name="submit" type="submit" value="submit">
</form>
My Javascript:
<script type="text/javascript">
function setval()
{
if (document.forms["ppal"].os0.value.indexOf("XX") > -1) {document.getElementById("amount") = document.getElementById("amount")+2};
}
</script>
There are a couple of problems with the script. First, it is calling document.getElementById("amount"), but there is no element with an ID "amount". You might want to change this:
<input type="hidden" name="amount" value="<?=$res[0]?>">
to this:
<input type="hidden" id="amount" name="amount" value="<?=$res[0]?>">
Second, when the script calls document.getElementById("amount"), it gets a reference to the input element, not the value the user typed into the element. You'll need to use the .value property of the input element to get what the user typed. See http://www.w3schools.com/jsref/prop_text_value.asp for more information about the /value property.
Keep in mind that the value property is a string, not a numeric, so you'll also have to convert using something like parseInt() before doing arithmetic.

Select list is populated correctly but value not included in POST

I have a webpage that uses a JavaScript function to populate a second dropdown box when an item from a first dropdown box is picked. The function creates the second drop down changing this:
<td>
<form action="http://website/addToDepartment.php" method="post">
<div id="nondepartment">
</div>
</td>
to this:
<td>
<form action="http://website/addToDepartment.php" method="post">
<div id="nondepartment">
<select name="personName">
<option value="Bob" name="personName">Bob</option>
<option value="Jim" name="personName">Jim</option>
<option value="Tom" name="personName">Tom</option>
</select>
</div>
</td>
My problem is that when the form button is pressed it does not POST the personName value chosen from the created list. If I write exactly the same code manually, so the function is not called, then it works. If I use the function to create the list it doesn't (no string at all gets POSTED). Why might this be?
You may have a conflict with the name property. Remove the name property from all of the options;you only need it on the select element. Also, make sure (recommend using Firebug) that the markup you are giving above is literally what does get produced; I've had before where injecting elements aren't in the <form> tag as expected, depending on how it's used sometimes.
You are not closing your form tag. Probably there lies your issue.
The HTML generated content should work to POST your values. Probably because the FORM is not closed, the browser will close it for you on a spot you do not expect.
Also you only need a name attribute on your SELECT.
Try this.
<td>
<form action="http://website/addToDepartment.php" method="post">
<div id="nondepartment">
</div>
</form>
</td>
<td>
<form action="http://website/addToDepartment.php" method="post">
<div id="nondepartment">
<select name="personName">
<option value="Bob" >Bob</option>
<option value="Jim" >Jim</option>
<option value="Tom" >Tom</option>
</select>
</div>
</form>
</td>

How do I set my HREF to text from an input field and a select list?

I am trying to set my HREF of my button to the text that was in the input field and the selected option from my select list, when the user clicks the Search button.
<div>
<div>
<input type="text" value="Keywords" style="width:206px" />
</div>
<div style="clear:both">
<select>
<option value="Test">Test</option>
</select>
</div>
<div>
<button>Search</button>
</div>
</div>
How do I set the href from the value of the input box and the selected value of the select list? I might need to create a form for this but I thought I could get away with something a little simpler. I just need to compile the search string and redirect the user to the appropriate page, since the search engine is already built.
Thanks!
Edit 1
Sorry guys I am using php to load the select list but I am not able to provide the code for how the select list gets populated since it has company sensitive information in it. I shouldn't have included that.
Using javascript, you can retrieve and value of a form field and handle it to what you need.
Suppose the select ID's select and the link ID's is link:
var value = document.getElementById('select').value;
document.getElementById('link').setAttribute('href', value);
With PHP only (no jQuery, no Javascript) you would use a submit-button in your form and work with $_POST:
1st your form (stripped down to basics):
<form method="post">
<input name="keywords" type="text" value="Keywords" style="width:206px" />
<select name="options">
<option value="Test">Test</option>
</select>
<input type="submit" name="ok" value="ok" />
</form>
2nd, on the beginning of your php-page that holds that form:
if (isset($_POST['ok'])) { // submit has been clicked...
if (isset($_POST[keywords])) { // there's input in keywords
$keywords = $_POST['keywords'];
// sanitize $keywords to prevent sql-injection
// go to the page you want to call...
// assuming there's no output before header ...
// and $keywords is in the right format ...
// and you retrieved $_POST['options'] to do sth with that, too
header('Location: http://www.url.com/page.php?key=$keywords');
} else exit('no keywords entered!');
}

Categories

Resources