stay at the same page after refresh - javascript

i have a page containing a form, there's a javascript listener on input type select , the event is onchange, depending on the option chosen from the select
the page will display a block of inputs (div), i am using hide and show to display or hide a block of html elements, one of those divs (div 2) has an input type select also with onchange event with ajax call . my first problem is that after hitting validate button of the form browser brings the default div i want that he stay at the last previous div , second problem is that div 2 after refresh the ajax call does not bring any data , its logical since the event is on change.
so want if div 2 has been displayed , the ajax call works after refresh .
this my html code
<form id="boxpanel" class="form-panel" method='POST' enctype='multipart/form-data' action='<?php echo URL.htmlspecialchars('ads');?>'>
<div>
<label for='catego'><b>categories: </b><span>(*)</span></label>
<span><select name="catego" id="catego">
<option value='0'>select a category </option>
<?php
foreach($this->categories as $key => $value) { ?>
<option value=<?php echo $value['id'];?> <?php if (isset($_POST['catego']) && $_POST['catego'] == $value['id']){ echo 'selected';}else{ echo '';}?>> <?php echo $value['categorie'] ;?></option>
<?php
}
?>
</select><br /></span>
</div>
<div id="div12" class="hide">
<br />
<div>
<label for='mark'><b>cars:</b> <span>(*)</span></label>
<select name='cars' id='cars' onchange="showHint(this.value)">
<option value=0>s1</option>
<option value=2>s2</option>
<option value=3>s3</option>
</select>
</div>
<br />
<div>
<label for='categos'><b>Models:</b></label>
<select id="txtHintts" name="model" class="form-control">
</select>
</div>
<br />
</div>
<div id="div13" class="hide">
<br />
<div>
<label for='wheels'><b>wheels:</b> <span>(*)</span></label>
<select name='wheels' id='wheels'>
<option value=0>c</option>
<option value=2>v</option>
<option value=3>v</option>
</select>
</div>
<br />
<div>
<label for='wheels'><b>colors:</b> <span>(*)</span></label>
<select name='colors' id='colors'>
<option value=0>a</option>
<option value=2>d</option>
<option value=3>c</option>
</select>
</div>
<br />
</div>
</div>
this is how i make hide and show works
<script>
function catego() {
if ($('#catego').val() == 1 ) {
$('#div12').removeClass('hide');
$('#div13').addClass('hide');
}
if ($('#catego').val() == 2) {
$('#div12').addClass('hide');
$('#div13').removeClass('hide');
}
}
$('#catego').on('change', catego);
$( document ).ready(function() {
catego();
});
</script>
this is my ajax call
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHintts").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHintts").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/gethint?q=" + str, true);
xmlhttp.send();
}
}
</script>

Remove the inline calling of
<select name='cars' id='cars' onchange="showHint(this.value)">
Call this method in the js after the show/hide is done.
Also, keep all the js events inside document.ready.

Related

Activate textbox on change of an item in Drop down in HTML

I am trying to do the following:
I have drop down menu with four options in it. When I choose Shipped a text box should enabled. So I tried the following:
<div class="col-md-3">
<select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" <?php if ($dispatch_status == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatch_status == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatch_status == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
<option value="Shipped" <?php if ($dispatch_status == "Shipped") echo "selected='selected'";?> >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
Java script:
<head>
<script type="text/javascript">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
</script>
</head>
Doesn't seem to trigger? I don't see log on console too. What could be wrong here?
Update:
I have pasted the html code here:
https://justpaste.it/6zxwu
Update
Since you've now shared your other code I think I know what you want. You have multiple modals, each with a select list and shipping_notes textbox which should be enabled when the selection is Shipped for that particular modal. I've modified your HTML to get this working.
I've updated your HTML a bit. You have multiple elements with the same ID. HTML IDs should be unique. If you want to target multiple elements it's safer to use class (or data-) attributes. I've added class="order-status" to each select and class="shipping_notes_txt" to each textbox. I've used element.querySelector() and document.querySelectorAll() to select DOM elements.
The snippet below mimics two modals. When the select is updated, it only enables/disabled the textbox within the same form element.
// wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
// get all select elements with class=order-status
var selects = document.querySelectorAll('.order-status');
// iterate over all select elements
for (var i = 0; i < selects.length; i++) {
// current element
var element = selects[i];
// add event listener to element
element.addEventListener('change', function()
{
console.log(this.value);
// get the form closest to this element
var form = this.closest('form');
// find the shipping notes textbox inside form and disable/enable
if (this.value == 'Shipped') {
form.querySelector('.shipping_notes_txt').disabled = false;
} else {
form.querySelector('.shipping_notes_txt').disabled = true;
}
});
// default value if status == Shipped: enable textbox
if (element.value == "Shipped")
{
var form = element.closest('form');
form.querySelector('.shipping_notes_txt').disabled = false;
}
}
});
.modal1 {
display:inline-block;
vertical-align:top;
padding: .5em;
padding-bottom:5em;
border: 1px solid black;
}
<div class="modal1">
<h3>First Modal</h3>
<div id="edit1" class="modal fade" role="dialog">
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus1" name= "ostatus">
<option value="Uploaded" selected='selected' >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped">Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes1" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
<div class="modal1">
<h3>Second Modal</h3>
<div id="edit20" class="modal fade" role="dialog" >
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus20" name= "ostatus">
<option value="Uploaded" >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped" selected='selected' >Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes20" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
Add onchange to your <select>
<select class="form-control" id="ostatus" name= "ostatus" onchange = "statuschange()">
And change the JavaScript to :
<script type="text/javascript">
function statuschange(){
var drpDownValue = document.getElementById('ostatus').value;
if (drpDownValue == 'Shipped')
{
document.getElementById('shipping_notes').disabled = false;
}
else
{
document.getElementById('shipping_notes').disabled = true;
}
}
</script>
assuming everything on the server side this works HTML comes first
<div class="col-md-3"> <select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" selected="selected" >Uploaded</option>
<option value="Processing" >Processing</option>
<option value="Dispatched" >Dispatched</option>
<option value="Shipped" >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});

Showing Div Not Working On Select Using Javascript

I am trying to show the FILE DIV if the user selects the doctor value in the select statement. I know the if statement works because I also print the value in the console which works perfectly fine. I toggle my divs in the same exact manner in my other webpages so I'm not understanding what's going on with this one in particular.
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}
}
.hidden{
display : none;
}
<div>
<select id="accountType" name="type" class="form-control" onchange="viewFile()">
<option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
****************************************EDIT-WORKAROUND**********************
Since my code refused to work, I added a line of code with 'head' being the title and not a real value. Thanks to everyone who contributed. I took out the hidden class altogether but when I add it, it still doesn't work correctly.
function viewDocFile() {
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if (type === 'regular' || type === 'head') {
file.style.display = "none";
console.log(type);
} else {
file.style.display = "block";
console.log(type);
}
}
***************************FINAL-EDIT************************
Kept the original code, but added the CSS inline.
<div class="form-group col-md-6" id="doclicense" style="display:none;">
Works perfectly now.
Here is an example of how this code should be written (even if there are still horrors)
// declare them here and not in a function where they will be redone each time the function is called
const
file_IHM = document.querySelector('#doclicense')
,
type_IHM = document.querySelector('#accountType') // and not with .value ...!
;
type_IHM.onchange = function()
{
file_IHM.style.display = (this.value==='doctor')?"block":"none";
console.log('type_IHM.value', this.value );
}
#doclicense { display : none; }
<div>
<select id="accountType" name="type" class="form-control" > <!-- let the js in the js part -->
<option required>Account Type</option>
<option value="doctor" id="doctor" >Doctor</option>
<option value="regular" id="regular" >Regular Account</option>
</select>
</div>
<div class="file-class" id="doclicense"> <!-- do not use class="hidden... -->
<input type="file" name="license" />
<input type="submit" /> <!-- there is no form anywhere... why don't you use <button> ?? -->
</div>
If that what your code really looks like, did you add your js in a <script></script> tag?
Or do you want to toggle the hide and show of the div?
if so this answer may help
<select id="accountType" name="type" class="form-control" onchange="viewFile()"><option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
<script>
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}else{
file.style.display = "none";
console.log(type);
}
}
</script>

hide the extra spacing taken by visibility:hidden

hello i want to hide the extra spacing taken by visibility:hidden. In the code when i select sort by date then it is replaced by default content, but when select sort by topic it comes under sort by date output. But i don't want this. I want to replace o/p of sort of topic to sort by date. I think it comes because of using visibility:hidden. Can anyone suggest me how i remove that space. I used display:none too, but no use.
<html>
<head>
<script>
function onloadfun()
{
document.getElementById("hideall").style.visibility="hidden";
}
function optionCheck()
{
if( document.getElementById("sorting").value=="bydate")
{
document.getElementById("topic1").style.visibility ="visible";
document.getElementById("topic").style.visibility ="hidden";
document.getElementById("showByDefault").style.display ="none";
}
if( document.getElementById("sorting").value =="bytopic")
{
document.getElementById("topic1").style.visibility ="hidden";
document.getElementById("topic").style.visibility ="visible";
document.getElementById("showByDefault").style.display ="none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if(option=="s")
{
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br /><br /><hr /><br /><br />
<?php include 'connection.php'; ?>
<div id="showByDefault">
<?php
echo "default content";
?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
</html>
Some reading:
visibility
The visibility CSS property has two purposes:
The hidden value hides an element but leaves space where it would
have been. The collapse value hides rows or columns of a table. It
also collapses XUL elements
display
In addition to the many different display box types, the value none
lets you turn off the display of an element; when you use none, all
descendant elements also have their display turned off. The document
is rendered as though the element doesn't exist in the document tre
An example based on your code but using display and setting it by a class using Element.classList.
var sorting = document.getElementById('sorting'),
showByDefault = document.getElementById('showByDefault'),
topic = document.getElementById('topic'),
topic1 = document.getElementById('topic1');
sorting.addEventListener('change', function optionCheck(e) {
var target = e.target;
if (target.value === 's') {
console.log('Do something here.');
} else if (target.value === 'bydate') {
topic1.classList.remove('hide');
topic.classList.add('hide');
showByDefault.classList.add('hide');
} else if (target.value === 'bytopic') {
topic1.classList.add('hide');
topic.classList.remove('hide');
showByDefault.classList.add('hide');
}
}, false);
#sorting {
width: 140px;
}
hr {
margin-top: 2em;
margin-bottom: 2em;
}
.hide {
display: none;
}
<form name="form">
<select id="sorting">
<option value="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<hr>
<div id="showByDefault">"default content";</div>
<div id="topic1" class="hide">"hiding 1";</div>
<div id="topic" class="hide">"hiding 2";</div>
The example is using unobtrusive JavaScript and unobtrusive CSS.
The principles of unobtrusive JavaScript
Change your code as follows.
I preferred to use display:block and display:none instead set visiblity
and also recommend jquery $(selector).show() and $(selector).hide() method.
<html>
<head>
<script>
function onloadfun() {
document.getElementById("hideall").style.display = "none";
}
function optionCheck() {
if (document.getElementById("sorting").value == "bydate") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "block";
document.getElementById("topic").style.display = "none";
document.getElementById("showByDefault").style.display = "none";
}
if (document.getElementById("sorting").value == "bytopic") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "none";
document.getElementById("topic").style.display = "block";
document.getElementById("showByDefault").style.display = "none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if (option == "s") {
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br />
<br />
<hr />
<br />
<br />
<?php //include 'connection.php'; ?>
<div id="showByDefault">
<?php echo "default content"; ?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
Try changing above three function in your code.
Use display:none instead of visibility hidden.
See example: http://www.w3schools.com/css/css_display_visibility.asp

Form submitted though Ajax is submitting multiple times

When I submit this form though Ajax, Ajax posts it multiple times, sometimes posting it up to 10 times, even though the submit button is only clicked once. I don't understand why it is doing this. Any help would be great!
Here is my code:
<script type="text/javascript">
var messageDelay = 2000;
$( init );
function init() {
$('#messageform').show().submit( submitForm );
$('#rtypeshow').hide();
$('a[href="#messageform"]').click( function() {
$('#content').fadeTo( 'slow', .2 );
$('#messageform').fadeIn( 'slow', function() {
$('#senderName').focus();
} )
return false;
} );
$(document).ready(function (){
$("#messagetable").load("messagetable.php");
$("#etype").change(function() {
if ($(this).val() != "0") {
$("#rtypeshow").show();
$('#datepicker').attr('required', 'required');
}else{
$("#rtypeshow").hide()
$("#allowed").hide;
$('#datepicker').removeAttr('required');
$('#allowed1').removeAttr('required');
}
});
});
$(document).ready(function (){
$("#rtype").change(function() {
var selection = $(this).val();
if (selection == "1") {
$("#allowed").show();
$('#allowed1').attr('required', 'required');
}else{
$("#allowed").hide();
$('#allowed1').removeAttr('required');
}
});
});
}
function submitForm() {
var messageform = $(this);
if ( !$('#ename').val() || !$('#message').val() ) {
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
messageform.fadeOut().delay(messageDelay).fadeIn();
} else {
$('#sendingMessage').fadeIn();
messageform.fadeOut();
$.ajax( {
url: messageform.attr( 'action' ) + "?ajax=true",
type: messageform.attr( 'method' ),
data: messageform.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#ename').val( "" );
$('#message').val( "" );
$('#datepicker').val( "" );
$('#allowed1').val( "" );
$('#allowed2').val( "" );
$('#allowed3').val( "" );
$('#allowed4').val( "" );
$("#messagetable").load("messagetable.php");
$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
$('#messageform').show().submit( submitForm );
} else {
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#messageform').delay(messageDelay+500).fadeIn();
}
}
</script>
<form id="messageform" action="message_forward.php" method="post">
<p>
<label for="ename">Event Name</label>
<input name="ename" type="text" id="ename" required="required">
</p>
<p>
<label for="message">Message</label>
<span id="sprytextarea1">
<textarea name="message" id="message" required="required"></textarea>
<span id="countsprytextarea1"> </span><span class="textareaRequiredMsg">A value is required.</span><span class="textareaMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
<p>
<label for="etype">Response Required</label>
<select name="etype" size="2" id="etype">
<option value="0" selected="selected">No</option>
<option value="1">Yes</option>
</select>
</p>
<div id="rtypeshow" style="display:none;">
Event Resender End Date:
<span id="sprytextfield1">
<input name="datepicker" type="text" id="datepicker" size="10">
MM/DD/YYYY <span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br>
Send Response To: <select name="eforward" id="eforward">
<?php
do {
?>
<option value="<?php echo $row_Recordset1['cphone']?><?php echo $row_Recordset1['provider']?>"><?php echo $row_Recordset1['fullname']?>-SMS Message via Cell Phone</option>
<option value="<?php echo $row_Recordset1['email']?>"><?php echo $row_Recordset1['fullname']?>-Email Message</option>
<?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
$rows = mysql_num_rows($Recordset1);
if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
}
?>
</select><br>
<label for="question">Question for responses</label>
<input type="text" name="question" id="question" maxlength="18"><br>
<label for="rtype">Response Type</label>
<select name="rtype" size="3" id="rtype">
<option value="0" selected="selected">Standard Yes/No Response</option>
<option value="1">Create Responses</option>
<option value="2">Get Users Own Response</option>
</select>
<div id="allowed" style="display:none;">
<h4>Response Options</h4>
<label for="allowed1">Option 1</label>
<input type="text" name="allowed1" id="allowed1" maxlength="12" placeholder="Required">Max Length = 12
<label for="allowed2"><br>
Option 2</label>
<input type="text" name="allowed2" id="allowed2" maxlength="12" placeholder="Optional">Max Length = 12
<br>
<label for="allowed3">Option 3</label>
<input type="text" name="allowed3" id="allowed3" maxlength="12" placeholder="Optional">Max Length = 12
<label for="allowed4"><br>
Option 4</label>
<input type="text" name="allowed4" id="allowed4" maxlength="12" placeholder="Optional">Max Length = 12
</div>
</div>
<input name="submit" type="submit" value="Send Messages">
</form>
Additional Comments:
Sending a message a second time seems to make it even worse then if the page is refreshed before sending another message.
It looks like your code is attaching the submitForm function multiple times to the submit handler.
In your submitFinished function you attach the handler again:
$('#messageform').show().submit( submitForm );
You can check this by refreshing the page then submitting the form. If it only submits once after refresh then multiple times after that you know that is the problem.

Javascript Form Validation Issue (<SELECT> Tag)

$(document).ready(function(){
$('#userForm').submit(function(){
user_id = $('#user_id').val();
valid = true;
if (user_id > 0) {
$('#user_id').removeClass('error');
} else {
valid = false;
$('#user_id').addClass('error');
}
return valid;
});
});
The above code should add a class to the user_id select I am using. This code snipet I am using on another page and it works fine but this one just seems to not like me. I have checkec all the variable names and its still not working.
This is validationg a SELECT (drop down menu)
Here it the relative HTML
<form method="post" action="index.php?action=save&course_id=<?php echo $_REQUEST['course_id']?>" id="userForm">
<input name="company_id" value="<?php echo $companyData->id?>" type="hidden" size="20" />
<select name="user_id" id="user_id" class="">
<option value="0" selected="selected">Select a User</option>
<?php if (count($userListData) > 0) {
foreach ($userListData as $userList) { ?>
<option value="<?=$userList->id?>"><?=$userList->firstname?> <?=$userList->surname?></option>
<?php } } ?>
</select>
<input name="submit" type="submit" value="Assign this user" />
</form>
Try:
if (user_id.length > 0)
This checks if there's a value for user_id at all, but if the select contains values like "-123" or "0" you might want to try a different approach:
if(user_id.length > 0) {
if(parseInt(user_id) > 0) {
// Has a value and is bigger than zero
}
}

Categories