Chrome Auto-checked radio button, hidden div with "required" blocking POST - javascript

EDIT 3: Ahha... some progress. The problem was actually in some code below the divs that I left out (updated HTML below to reflect). The second div contains a "required" input, so simply changing the div to display=none via javascript doesn't actually make the page entirely ignore the hidden Div. So a slight change to the angle of my question - how would I adjust the code below to completely ignore the hidden div, so that the required field is not read?
EDIT 2:I have tried removing the 2nd block of JS code below and inserting the dynamic PHP code directly into the input and div tags to change the display - still no luck.
EDIT 1: Just to confirm, the solution to a similar question doesn't work in this case: Auto checked radio buttons and php form processing - How to avoid blank field? it seems that the Chrome team have made changes in later versions that make this solution redundant.
A user on the website can select either Points or Stamps - I get the value from the Database via PHP and the form should have the relevant radio button checked and only show the Div related to that radio button.
Everything works fine, however, unless I manually change the radio button it will not let me POST the form i.e. I cannot post with value selected automatically from the DB - it seems a similar problem to this (Chrome Browser Ignoring AutoComplete=Off) - but no matter what I do with Chrome autocomplete it doesn't work. Also the page is recognising the radio as checked because it shows my dot in the right place. (EDIT 3: still unsure why this works in Mozilla but not Chrome - but latest Edits make this less important)
Heres my JS that shows the right Div if a radio button is changed:
$(function () {
var $divs = $('#option > div');
$('input[type=radio]').change(function() {
$divs.hide();
$divs.eq( $('input[type=radio]').index( this ) ).show();
});
});
This JS sets the correct radio button based on DB and shows the correct div when the page loads:
$(function() {
var $radios = $('input:radio[name=selection]');
var $type = "<?php echo $type; ?>";
if($type === 'points') {
$radios.filter('[value=points]').prop('checked', true);
document.getElementById('pointsdiv').style.display = 'block';
document.getElementById('stampdiv').style.display = 'none';
}
else if($type === 'stamp') {
$radios.filter('[value=stamp]').prop('checked', true);
document.getElementById('stampdiv').style.display = 'block';
document.getElementById('pointsdiv').style.display = 'none';
}
});
My HTML and PHP:
$type = $_SESSION['user']['type']; //Note: This is actually set at the very top of the page i.e. before the JS
<form autocomplete="off" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" role="form">
<input type="radio" id="selection" name="selection" value="points"></input><label>Points</label>
<input type="radio" id="selection" name="selection" value="stamp"></input><label>Stamps</label><br></br>
<div id="option">
<div id="pointsdiv">
//Points related information here
<input type="text" required="required"/>
</div>
<div id="stampdiv">
//Stamp related information here - below input is required so when pointsdiv is displayed, this entire div should not even load
<input type="text" required="required"/>
</div>
</div>
<button type="submit" class="button">Save</button>
</form>
Anyone have any ideas how I can load this page and post the form if I don't change the radio button - i.e. if it loads with "Points" checked and I click the Save button?

Input radio groups must have the same name but not the same id,
so you should change id="selection" for one of them.
If everything is in the same page and the page is in php,
then you have to wait for dom ready before setting input values.
There is a dynamic way without using javascript :
<input type="radio" <?=$type =='points'?='checked="checked"':''?> id="selection" name="selection" value="points">
The same thing you can do with the other radiobutton
and also with the divs pointsdiv and stampdivs

Related

Show a hidden div after a form submit page refresh

I have a div result_head which is hidden by default. Whenever I click a button which will provide options to select results, this hidden div will display as a heading for the form.
<div class="result_head" id="result_head" style="display: none"> >Results</div>
And the form code
<form method="post" id="form_result">
<div class="form-group">
<-----some drop down menus here --------->
<div class="form-group">
<button type="submit" name="result_submit" id="result_submit" style="display: none;margin:1%;" >Submit</button>
</div>
</form>
After the submit and after the page refresh, I need to display the heading for the result.
I tried different methods to achieve without any luck.
Tried Adding onclick and onsubmit finctions along with form submit
<button type="submit" name="result_submit" id="result_submit" style="display: none;margin:1%;" onclick="document.getElementById('result_head').style.display = 'block';">Submit</button>
Tried to echo CSS in php to display_head.
<div class="result_head" id="result_head" style="display: none" <?php if (isset($_POST['result_submit'])){ echo 'style="display:block !important;"'; } ?> >Results</div>
Also found a method echo entire div via php after form submit which will create the new div after form submit. But that option is not feasible for me as I need to display the head before submit as well.
Also while looking into some solutions, found an option to change the button type from sumbit to button and use jquery\ajax to submit the form. I may have to change my entire code for that.
Is there any other way to do it ?
How about the following:
<div class="result_head" id="result_head" style="display: <?php echo ($_POST['result_submit'] ? 'block' : 'none') ?>">Results</div>
It just changes the style from none to block when submited.
after submitting form you can store value in localStorage for example
localStorage.setItem('isHeadingVisible', true);
and add code which will check in every page load is header visible or not by checking this
if(localStorage.get('isHeadingVisible')){}
you can read more about localStorage here
but this will not work if user will use another browser after these operations, because user's localStorage will be emty in new browser, so I would suggest to use backend data here, or check in every page load if localStorage.get('isHeadingVisible') is undefined and form is submitted, set localStorage.setItem('isHeadingVisible', true);

Radio option on view that updates and changes view?

I think that my problem isn't very hard -but I'm pretty new to this and having issues finding an easy solution.
I have a form that collects a few items, and an output page that creates a table based on those few items. For example, one of the form options is "Which leg is affected?" And you must choose either "Left, Right, Both".
I would like to create a radio selection option on the view so that the person using this tool won't have to click the back button to update this one field. The table that is built changes based on this one selection, so it would be nice to see those changes without resubmitting the form.
If anyone can point me in the right direction - either JavaScript or some method that involves re-sending the form values from the view - I would be very grateful.
I believe what you're describing is exactly what the idea of "single page app" style coding with Javascript is for - modifying the page with logic without necessarily needing to make a server request. I.e., you want to make an "application." Albeit a simple one.
What I recommend you look into is "event handlers," specifically the click handler.
So, if you had html that looked like: (stolen from MDN's radio page)
<form id="radio_form">
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1"
name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2"
name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3"
name="contact" value="mail">
<label for="contactChoice3">Mail</label>
</div>
</form>
You could then have code that looked like
var radio = document.getElementById('radio_form');
radio.onclick = changeTable;
function changeTable(e){
// Do logic here to change table
}
The idea is your page is "waiting" for the form to be "clicked" (you could also look into onChange), and when it is clicked, a function is invoked that does further logic.
See here to figure out how to get the value of a selected radio.
See here for using javascript to insert a row into a table (what you may want to do in your changeTable function).
EDIT: One "gotcha" to look out for is if your script is running when the page is actually loaded. This can be a problem if your page loads asynchronously (doubtful). Just in case, also look into some kind of document.ready implementation: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
You can add an event listener for 'click' to each radio input and have the callback function modify the view in whatever way you want.
Here's an example:
const form = document.querySelector('.choice-form');
const display = document.querySelector('.display');
form.querySelectorAll('input[type="radio"]').forEach(input => {
input.addEventListener('click', () => {
display.innerHTML = "";
if (input.id === '1') {
display.innerHTML = "<span>You selected: <span class='red'>One</span></span>";
} else if (input.id === '2') {
display.innerHTML = "<span>You selected: <span class='blue'>Two</span></span>";
}
});
});
.red {
color: red;
}
.blue {
color: blue;
}
<div>
<form class='choice-form'>
<label for='choice'>Make a choice</label>
<input type='radio' id='1' name='choice'/>
<label for='1'>One</label>
<input type='radio' id='2' name='choice'/>
<label for='2'>Two</label>
</form>
<div class='display'>
</div>
</div>

Function works when button clicked but not when submitting the form

I have yet another question concerning this project but here's hoping ill learn a lot from it.
So I created a function, that creates a div inside a div (which will then contain a random number from dice roll) and it works when I add this function to a button click.
But clicking the button multiple times might not be ideal for a lot of dice, so I created a form and it shouldnt create the number of divs the user decides he wants, but it doesnt seem to work. I suspect it has to do with the form refreshing the page, so instead of handling the even withh addEventListener I used inline "onsumbit" and tried to return the function but it still doesnt seem to work. What am i doing wrong? Here is the HTML and JS bits:
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
and JS:
var numInput = document.querySelector("input");
function addDice(){
var div = document.createElement('div');
div.className = "diceStyle";
div.innerHTML = "<p> here will be a dice</p>";
document.getElementById('diceTable').appendChild(div);
};
function addMoreDice(){
for(var i = 0; i < numInput; i++){
addDice();
}
}
1.You should probably include onsubmit() in form tag and add a submit button inside form.
You can use onchange() method to invoke addMoreDice() whenever the value in input box is changed
you need to add onsubmit="yourfunction()" in side form tag
and than put an input type submit inside form tag like
<form action="#" onsubmit="addDice()">
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
<input type="submit" value="Submit">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
Each time you submit a form, it gets you to a different page. Instead you could have this code as shown below, (remove form tags)
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber"></input>
<input type="submit" onClick="addMoreDice()">
Clicking on submit after entering the input dynamically creates divisions per your need.

storing whole innerhtml design of a DIV to a variable

I am trying to fetch the whole innerHtml of a DIV to a PHP variable.
For this what I have done is to put the whole of the innerHtml into a Hidden field, and then call the Hidden field into php.
My code is:
<form method="post">
<div class="container" id="content">
<h1>Header1</h1>
<p>this is the para</p>
<textarea id="address" name="address"></textarea>
</div>
<input type="hidden" id="hidhtm" name="hidhtm"/>
</form>
In my JS file I have:
document.getElementById('hidhtm').value = document.getElementById('content').innerHTML;
In my PHP I have:
$test = $_POST['hidhtm'];
echo $test;
Can anyone please help me on this.
I wanted to do the same thing, and tried your method and it works.
In my test, the Javascript function which extracts the innerHMTL and places it in the hidden field of the form is called upon the user clicking a button which enabled the "submit" button (eg. acceptance of terms and conditions) but which does not actually submit the form. Therefore the hidden field was populated before the form was submitted. I haven't tried doing the same thing "onSubmit" but I suspect it might be too late to do so then.
I found that the material which could be inserted into the hidden field included all the values inserted by the user onto the form as well as things inserted by Javascript itself. All this could be picked up from the $_POST variable for the hidden field.
I needed to do this so that the PHP server could create a new form dynamically and send it back to the user.
function add_question(){
var count=document.getElementById("nofquest").value;
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes())
{
container.removeChild(container.lastChild);
}
for (i=1;i
please find text boxes in center how to align

Changing yes/no value in database, on click of hyperlink

sorry about my limited coding skills and so on, but hopefully you can see what I am attempting. I want to scrap the form checkboxes and have 2 simple 'yes' 'no' hyperlinks, dependant on if image is hidden or shown. Will javascript do this? This is what I have so far, which was working but like I say, I just want 2 links instead of checkboxes.
if ($_POST['option']) {
if ($_POST['option'] == 'yes') {$hidden = 0;}
if ($_POST['option'] == 'no') {$hidden = 1;}
#mysql_query('UPDATE Image SET Hidden = ‘.$hidden.’ WHERE ID = '.$image->ID.'');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
<p>Show image?
<form method="post" action="?">
<input type="checkbox" name="option" value="yes">Yes
<input type="checkbox" name="option" value="no" >No
<input type="submit" name="submit" value="Go!" />
</form>
So then I can have HTML such as -
Show Image? Yes / No
(This image is shown) or (this image is not shown)
Any points in the right direction would be greatly appreciated, Many thanks!
Hi Guys, Sorry, I don’t think I explained myself properly.
All images have a default value of ‘Hidden = 0’ in the image database table, so they are all currently shown on the page. Here is the code -
// there is some SQL here that fetches all images
// here is the actual code that shows images:
foreach($ids as $id)
{
$tmp = new Image($id,true);
if (!$tmp->ID) continue;
<p>
<img src=”/myurl/’.$tmp->ID.’.jpg”>
</p>
}
What I want is, in that loop, underneath each image tag, is to have some HTML :
<p>Show Image? Yes / No </p>
I want the ‘yes’ and ‘no’ to be hyperlinks, which state will depend on the images ‘Hidden’ value.
So if the image is shown (all currently are), the word ‘Yes’ won’t be a clickable hyperlink, only ‘No’ will be.
If I then click ‘No’ I need it to post a query on click, to set Hidden = 1, to hide the image.
If the image is already hidden, then ‘Yes’ would be the only clickable link, which if clicked would post value Hidden = 0, so the image is shown.
I hope that makes sense. The other problem I have is the fact that there are multiple images, so the form or whatever system I use, needs to distinguish which image it is changing the Hidden value for.
In the code, the image’s unique id field is accessed like this: $tmp->ID
If you want hyperlinks just use something like
Yes
No
Also you will probably want to use single quotes ''s and not ‘'s for your query. Also I'd recommend using mysqli or PDO so you can use prepared statements instead of mysql_ functions which are prone to mysql injections.
Easiest way would be to use a hidden input field that will be submitted with the rest of your form and using javascript to change the value of that hidden field.
HTML:
<p>Show image?
<form method="post" action="?">
<input type="hidden" name="option" value="default" />
Yes
No
<input type="submit" name="submit" value="Go!" />
</form>
JS (requires JQuery):
$(".option").click(function (e) {
$("input[name=option]").val($(this).attr("data-value"));
});
Then when you submit the form $_POST should have the "option" value.
Try this
if(isset($_GET['cmd']))
{
if($_GET['cmd']=='yes')
{$hidden = 0;}
if($_GET['cmd']=='no')
{$hidden = 1;}
#mysql_query('UPDATE Image SET Hidden = '.$hidden.' WHERE ID = '.$image->ID.'');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<p>Show image? <br />
Yes <br /> <!--Replace page url according to yours -->
No
Just to reaffirm, the following form is my latest revision and works perfectly, updating the database and radio buttons on the page. However, it is still not the solution I want. I want hyperlinks only, as in the above examples posted by Boshi and Class, but for some reason my site won't accept those urls, the system churns me out to a different page and nothing works.
Here is the latest revision which works. Is there another solution? -
if ($_POST[''.$tmp->ID.'']) {
if ($_POST[''.$tmp->ID.''] == 'yes') {$hidden = 1;}
if ($_POST[''.$tmp->ID.''] == 'no') {$hidden = 0;}
#mysql_query('UPDATE Image SET Hidden = '.$hidden.' WHERE ID = '.$tmp->ID.' LIMIT 1');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
<p>Hide image?
<form method="post" action="?">
<input type="radio" name="'.$tmp->ID.'" value="yes" '.($tmp->Hidden ? 'checked' : '').'>Yes
<input type="radio" name="'.$tmp->ID.'" value="no" '.(!$tmp->Hidden ? 'checked' : '').'>No
<input type="submit" name="submit" value="Go!" />
</form>

Categories