Automatically submit form with first option (PHP) - javascript

I have a project in which I must do something like this:
when a user's page loads, he gets a personalized select box (with some options generated by PHP for him) and then, when he changes the option, I must change the rest of the content (on the same page).
for example, let the select box for a kind of user be:
Main content
Tools
Now, my idea was to have a
<form action="processing.php">
<select name="choice" onChange="submit();"> etc. which should pass the user's choice to processing.php. The problem is, I want the first option to be automatically selected and the content for that option to appear when the page loads - somehow like the first option to be automatically submitted.
Also, different kind of users should get different options, and I thought I can use a single page to process these requests. Is this achievable?
Can you please help me with an idea on how to submit that form automatically with the first generated option? Thank you.

You can use the onChange Event of the selection. In the handler you can then do the redirect
let sel = document.getElementById('yourselect');
let form = document.getElementById('yourform');
sel.onchange = function() {
form.submit()
}

You can easily bind the select change with Javascript. Here is the example with jQuery:
$('#mySelect').on('change', function(){
// Do your staff
$('#myForm').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<select id="mySelect" method="post" action="processing.php" name="select_name">
<option value="">Select One</option>
<option value="http://google.com">Google</option>
</select>
</form>

Related

Dynamically load JSON into a datalist (vanilla JS)

I've been spending the past couple of days researching on W3C and SO (this being the closest issue I found to mine), to dynamically load a "static" JSON into a dynamically created datalist.
More details on what I'm trying to achieve - I'm trying to create a form to add records to a database; default form allows to add one record, but there's a button to dynamically add another set of empty fields to submit multiple records at once. Once all form is filled in, this is sent to PHP for processing. I'm using bootstrap for the frontend (though I'll try to clean the code for readability).
Load page for the first time, save the JSON into a "HTML variable". Note the page has already one datalist.
Should the user click on the button to add another set of fields, these appear (including an additional datalist)
Objective: this newly created datalist should be populated with the JSON saved in the HTML Variable in point no. 1
Two questions:
Is this doable? As in, do HTML vars have a persistent scope even if I change the DOM?
If so, what am I doing wrong in the code below?
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?do=addnewstructure" enctype="multipart/form-data">
<input list="datalistOptions" id="datalisttype1" name="deftype_ent[]" placeholder="Type to search..." onFocus="populate_datalist(types_json);">
<datalist id="datalistOptions">
<option value="first">First persistent option</option>
</datalist>
</div>
<div>
<label for="value_ent">Name</label>
<input type="text" name="defvalue_ent[]" id="value_ent">
</div>
<div>
<label for="relevance_ent">Relevance</label>
<select id="relevance_ent" name="relevance_ent">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<script>
var types_json = document.createElement("list_of_types");
var dataList = document.getElementById("datalisttype1");
var types_json = [<?php
echo json_encode($results_json); // This is coming from backend, it is valid JSON
?>];
// Loop over the JSON array.
function populate_datalist(which_dl)
{
which_dl.forEach(function(item) {
var option = document.createElement('option');
option.value = item.type_id;
option.text = item.name;
dataList.appendChild(option);
});
}
</script>
<button type="submit">Add</button>
</form>
I know this may be a noob question as I just started with js, only did BE languages so far. Thanks for your help! :)
For anyone stumbling upon this code in the future - I got it work and there are a variety of reasons why it wasn't working previously.
In brief:
function appendChild wasn't attaching options to the datalist but to the input
the JSON, although valid, didn't have single quotes
some of the variables weren't initialised, and failed when called for a function
the function was declared after the datalist (e.g. called before it was declared)
some others
TLDR; do not rely on the code above, even as an inspiration :)

Javascript onchange select boxes

So I have a drop down box that posts to the page on a submit button.
I am trying to remove the submit button and make it so it posts when you change the drop down as its a much better way to work!
The value = "submit_button" and it gets picked up by:
// Check if form has been submited
if ($_POST['submit_button'])
{
// If form has been submited set $newCookieValue variable, set cookie and refresh webpage
$newCookieValue=$_POST['dbselector'];
The code I am trying to use is:
<form>
<select name="dbselector" onchange="this.form.submit()" style="margin-left:0.5em;">
<option value="option_1" selected="selected">option_1</option>
<option value="option_2">option_2</option>
</select>
<noscript><input type="submit" value="submit_button"/></noscript>
</form>
When I change the drop down from option 1 to option 2 it reloads the page but I don't think its posting the values as I can check the values by adding this into the top of the page:
<br> <?php var_dump($_POST['dbselector']) ?>
<br> <?php var_dump($_POST['submit_button'])?>
and they both return NULL?????
You need to state in your form that you are using POST via method in order to tell the form which HTTP method to use:
<form method="post">
...
</form>

Javascript OnChange Script - Stop Form Submission

I have a project im working on, that needs a javascript OnChange Script for a dropdown box on media upload page.
I have a drop-down box with 2 options -'Yes' and 'No'. If the user selects 'No' i don't want the form to submit and possibly display a message saying why.
Is anyone able to provide a script to do this? I have to enter this on the attribute itself (eah attribute has the ability to have a OnChange script), i can change the attribute references to the specific ones needed. More of a general 'formula' for the script is needed.
Maybe i'm too vague and its not possible to make on the information i have given you.
Thanks in advance,
T.
first, write javascript code like this
<script>
function output()
{
var input = document.getElementById('input').value;
if(input==0){
alert("WHY???");
document.getElementById("out").value="why?";
}else{
document.getElementById("out").value="Ok";
}
}
</script>
and for the html code
<form>
<select name="input" id="input" onchange="output()">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<input type="text" id="out" name="out">
</form>
note: javascript not java

How to toggle forms using HTML <select> controls

I am currently developing a web application that requires me to register users according to their category. I have a combo-box in which the user can choose which type of user they are.
I want to do is show a relevant form according to the user's selected value. I'm am using PHP for all the functionality, but I'm a newbie to jQuery. Can anyone show how to implement this or else demonstrate a different way of doing this without reloading the page?
You can try using a category dropdown list as shown.
HTML Code
Dropdown
<select id="category">
<option value="#form1">Category 1</option>
<option value="#form2">Category 2</option>
<option value="#form3">Category 3</option>
</select>
Forms
<form id="form1">
</form>
<form id="form2">
</form>
<form id="form3">
</form>
jQuery Code
$(function(){
var forms = $('form'); //cache all Forms
forms.hide(); //hide initial
$('#category').on('change', function(){
forms.hide(); //on change hide all forms
var formId = $(this).val(); //get form id to show
$(formId).show(); //find form by its id in cached forms and show.
});
});
You can use jQuery show() and hide() functions:
Example:
$('#form1').hide();
$('#form2').hide();
$('#form3').show();
In this example you have forms defined as follows:
<form id="form1">...</form>
<form id="form2">...</form>
<form id="form3">...</form>
You can also get fancy with it and use fadeIn() and fadeOut() if you want some effects.
You can use jQuery toggle() function:
$('#your_form').toggle();
From the docs:
The matched elements will be revealed or hidden immediately, with no
animation, by changing the CSS display property. If the element is
initially displayed, it will be hidden; if hidden, it will be shown.
The display property is saved and restored as needed. If an element
has a display value of inline, then is hidden and shown, it will once
again be displayed inline.

How to ensure a <select> form field is submitted when it is disabled?

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.
The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
Disable the fields and then enable them before the form is submitted:
jQuery code:
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name is the name that you would normally give the <select>.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
I faced a slightly different scenario, in which I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect').find(':not(:selected)').prop('disabled',true);
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
Same solution suggested by Tres without using jQuery
<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">
<select id="mysel" disabled="disabled">....</select>
<input name="submit" id="submit" type="submit" value="SEND FORM">
</form>
This might help someone understand more, but obviously is less flexible than the jQuery one.
The easiest way i found was to create a tiny javascript function tied to your form :
function enablePath() {
document.getElementById('select_name').disabled= "";
}
and you call it in your form here :
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
Or you can call it in the function you use to check your form :)
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Just add a line before submit.
$("#XYZ").removeAttr("disabled");
Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled.
This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well.
Using jQuery:
jQuery(function($) {
$('form').submit(function(){
$('select option:not(:selected)', this).remove();
});
});
<select id="example">
<option value="">please select</option>
<option value="0" >one</option>
<option value="1">two</option>
</select>
if (condition){
//you can't select
$("#example").find("option").css("display","none");
}else{
//you can select
$("#example").find("option").css("display","block");
}
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements may be successful.
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

Categories

Resources