Jquery on page load with local storage default option not set - javascript

I know there are multiple posts out there for setting the default option using Jquery.
But i tried most of them, but not seems to be working.
Guess something wrong with my condition?
I just need to get the the default option Article Type on page load.
Code:
<select id="blogarticletype">
<option selected><?php echo $this->__('Article Type') ?></option>
<option><?php echo $this->__('All Types') ?></option>
<!--Begin To Retain Article type drop down in local storage after refresh-->
<script type="text/javascript">
if (localStorage.getItem('mySelectLocalstorageValue') === null) {
localStorage.setItem('mySelectLocalstorageValue', "articletype");
//document.write("All Types");
}
else {
if (localStorage.getItem('mySelectLocalstorageValue') === "article") {
document.write("Articles");
} else if (localStorage.getItem('mySelectLocalstorageValue') === "makers") {
document.write("Artists & Makers");
}
</script>
</select>
On page load:
jQuery( document ).ready(function() {
jQuery('#blogarticletype option:selected').text();
if (jQuery('#blogarticletype').length) {
jQuery('#blogarticletype').val(localStorage.getItem("mySelectLocalstorageValue"));
}
});
But when page loads, i get empty value shown in the drop down.
If i manually set in the inspect for option value as selected="selected" then it shows, but not on page load

There is change on this line
$('#blogarticletype [value='+localStorage.getItem("mySelectLocalstorageValue")+']').attr('selected', 'true');
and it works. Working Demo: https://codepen.io/creativedev/pen/Qxvjmz

Related

Is it possible hide a specific field after user selection of another field?

I need to create an IF that allow me to define a specific rule.
I have a customer portal page where customers can open tickets.
The form is developed in order to insert some information like: “software product” and “environment” both are defined as dropdown list. In addition we have other fields like “Suite version”.
The IF I need is:
If (software product = ‘TEST’) then HIDE the field “Suite Version”
It is needed because the value “TEST” will open a new level of the “Software Product” field.
I can use Jquery JavaScript.
Many thanks.
is this what you want ?? check below code
$( document ).ready(function() {
$('#SoftProd').change(function(){
$('#pp').html($(this).val());
if($(this).val() == "Test")
{
$('#SuiteVersion').hide();
}
else
{
$('#SuiteVersion').show();
}
});
});
<Select id="SoftProd"> Software Product
<option selected value="">Select option...</option>
<option value="Test">Test</option>
<option value="other">other</option>
</Select>
<input type="text" Placeholder="Suite Version" id="SuiteVersion" name="SuiteVersion">
<!--Jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
you can try js
css
#Suite_Version {
display: none;
}
JS
var software_product = $('#software_product').val();
if (software_product === "test") {
$("#Suite_Version").hide();
} else {
$("#Suite_Version").show();
}
I tried to use this code but unfortunately doesn’t work.
Consider that I am new in this programming language.
jQuery(document).ready(function()
var software_product = $('#helpdesk_ticket_custom_field_cf_product_1815896').val();
{
if (software_product === "AMHS"){
Jquery("#helpdesk_ticket_custom_field_cf_suite_version_1815896").parent().parent().hide();
}
else {
Jquery("#helpdesk_ticket_custom_field_cf_suite_version_1815896").parent().parent().show();
}
});

Using Jquery to change form based on user input

I have a form with a select tag. I need my form to change based on the selection from the user. I am given to believe that the easiest way to do this is to use JQuery.
Here is my code:
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
</div>
<div id="addhtml"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
alert("event triggered");
var val = $(this).val();
if (val == "number" || val == "symbol") {
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
} else if (val == "letter") {
$("#addhtml").html(<?php include("html/form_letter.html"); ?>);
} else {
$("#addhtml").html(<?php include("html/form_other.html"); ?>);
}
});
});
</script>
Note: the php while statement just sets up the current three options of "number", "symbol" or "letter" with ids of 1,2 and 3 respectively
When I change the category, it does not trigger the jquery.change()
I would like to code the form without using the addhtml div but am willing to use it if necessary.
Questions:
Is the reason the change function is not being triggered because I am using php to set the values of the select options?
If so how can I resolve?
If not, why isn't it being triggered?
How can I accomplish my goal of not using the addhtml div?
Is there a better way to accomplish what I am going for?
Thanks in advance.
EDIT:
Answers to initial questions: As stated by bistoco, php is pre compiled by the server and sent in as html so the issue is not from using php to set the values of the select tag.
I have now determined that it is due to the content of my php include files. I have determined that it registers the change event and loads the content just fine if my file is simple like this:
"<div><label>New Number</label></div>"
but if I add any white space or \n characters for human readability like this:
"<div>
<label>New Number</label>
</div>"
Not only does it not work, but it also completely skips the change event.
New Questions: Does the jquery html function have a list of illegal characters that would cause it to fail? Why is it not even registering the change function when it doesn't like the contents of my php include file?
First thing that you must understand is that php runs on the server, all the output is rendered and sent as html code to the browser, and is not available there.
That said, you have at least 2 options :
1.- echo all form options, each one inside a div, that you can hide/show based on the selected choice.
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
<!-- ECHOING ALL FORM OPTIONS -->
<div class="option-form" id="form-option-symbol"><?php include("html/form_number.html"); ?></div>
<div class="option-form" id="form-option-letter"><?php include("html/form_letter.html"); ?></div>
<div class="option-form" id="form-option-other"><?php include("html/form_other.html"); ?></div>
</div>
<style>
div.option-form {
display:none; /* HIDE ALL DIVS BY DEFAULT */
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
// HIDE ALL DIVS
$('div.option-form').hide();
var val = $(this).val();
if (val == "number" || val == "symbol") {
$('form-option-symbol').show();
} else if (val == "letter") {
$('form-option-letter').show();
} else {
$('form-option-other').show();
}
});
});
</script>
2.- Using a template system or load partial html pieces with ajax.
PHP Is a pre-processor so adding later into the website is useless. Just create your form with either setting its html or by using .prepend() or .append() with your form elements.
<form class="myform">
</form>
and in jquery
$('.myform').html('<input type="submit">');
or
$('.myform').append('<input type="submit"');
EDIT :
Read your code wrong looked up
<?php include('test.html'); ?>
don't think that would work.
Instead of
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
and such, try
$("#addhtml").html("<?php include("html/form_number.html"); ?>");
so that the html will be treated as a string.
Also make sure the form files don't have tags such as html, head, and body, and only contain the actual form.
EDIT: I just saw that #nnnnnn already stated this, gotta give credit where credit is due
I think you might just need to change your variable "val" declaration to get your code to work.
I don't think
var val = $(this).val();
will work. Based on the comparison you are making, I believe it should be:
var val = $(this).children("option:selected").text();
which will allow you to get the text value of the select element's selected option.

Javascript adding option values

I am using the javascript code below to add option values to a select field.
<script type="text/javascript">
$("#location").append($("<option></option>").val("Any Location").text("Any Location"));
$("#location").append($("<option></option>").val("Location 1").text("Location 1"));
$("#location").append($("<option></option>").val("Location 2").text("Location 2"));
</script>
This works ok but as my form is setup with PHP, I need to use the following code so that the selected value is retained in the select field when the results page is shown.
<option value="Any Location"<?php if(isset($_SESSION['location'])) { if($_SESSION['location'] == "Any Location") { echo "selected";} } ?> >Any Location</option>
Is it possible to somehow integrate the PHP SESSION code with the javascript?
Thanks
Write it as JSON:
var dataLocation = <?php
if(isset($_SESSION['location']))
{
echo '{"location" : "'.$_SESSION['location'].'"}';
}
else {
echo '{"location" : "Unknown"}';
} ?>
Now JavaScript will parse this as valid code and you can retrieve the location with: dataLocation.location;
If you execute this at the top of the script you can do this:
$("#location").append($("<option></option>").val("Any Location").text("Any Location"));
$("#location").append($("<option></option>").val("Location 1").text("Location 1"));
$("#location").append($("<option></option>").val("Location 2").text("Location 2"));
//updated version:
var selectElement = $("#location > option[value='"+dataLocation.location+"']");
if (selectElement)
{
selectElement.attr("selected", true);
}
For this to work the value of the option needs to be identical to the location set in the session.

Using JQuery for refreshing page but not getting desire results

I am using Jquery for refreshing page i it is refreshing but when i select one option from my category it is refreshing and then my selected category be disappear but i want when i select any one option the page will be refresh but my selected option will also be the same which i selected hope you guys will understand my problem.
$(function() { $('select[name="cat"]').change(function() { location.href = 'insert_book.php?cat=' + $(this).find('option:selected').val(); }); });
<select id="rf" name="cat">
<option value='null'>Select your Desire</option>
<?php
include('includes/db.php');
$c_query="select * from categories";
$c_run=(mysql_query($c_query));
while($c_row=mysql_fetch_array($c_run)){
$c_id=$c_row['p_id'];
$c_title=$c_row['p_title'];
echo "<option value='$c_id'>$c_title</option>";
}
?>
</select>
Change your refresh code to this:
$(function() {
$('select[name="cat"]').change(function(ev) {
location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val();
});
});
Also move this JS code after the HTML code for the select element or wrap it with $(document).ready() like this:
$(document).ready(function(){
$('select[name="cat"]').change(function(ev) {
location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val();
});
});
Now in the loop code:
$selectedCategory = array_key_exists('cat', $_GET) ? $_GET['cat'] : 0;
while($c_row=mysql_fetch_array($c_run)){
$c_id=$c_row['p_id'];
$c_title=$c_row['p_title'];
echo "<option value='$c_id'".($selectedCategory == $c_id ? " selected='selected'" :"").">$c_title</option>";
}
Finally:
As Chris Baker mentioned stop using mysql_ and use mysqli_ or PDO.

How a toggle div be displayed when it's respective option is not "changed" but "selected"?

Very simple thing: on my form, I'm toggling among three divs on select option. Using this SO thread and so the JSFiddle to this. Just a simple jQuery change function. So, I'm not mentioning them again. I'm using the same form for inserting and editing data. Here I presented two divs of code what I'm with in a dummy form with minimized code:
<form>
<select name="choice_type" id="choice_type">
<option value="">Select One</option>
<option value="type1"
<?php
if ( isset($_POST['choice_type']) && $_POST['choice_type'] != '' ) {
echo ( $_POST['choice_type'] == 'type1' ? 'selected="selected"' : 'disabled="disabled"' );
} elseif( isset( $query_with_id ) && !empty($query_with_id[0]->choice_type) ) {
echo ( $query_with_id[0]->choice_type == 'type1' ? 'selected="selected"' : 'disabled="disabled"' );
} else {
echo '';
}
?>
>Type 1</option>
<option value="type2"
<?php
if ( isset($_POST['choice_type']) && $_POST['choice_type'] != '' ) {
echo ( $_POST['choice_type'] == 'type2' ? 'selected="selected"' : 'disabled="disabled"' );
} elseif( isset( $query_with_id ) && !empty($query_with_id[0]->choice_type) ) {
echo ( $query_with_id[0]->choice_type == 'type2' ? 'selected="selected"' : 'disabled="disabled"' );
} else {
echo '';
}
?>
>Type 2</option>
</select>
<input type="submit" name="publish" id="publish" value="Publish"/>
</form>
<div id="type1" class="togglediv hide-me">Type1</div>
<div id="type2" class="togglediv hide-me">Type2</div>
Please note: $query_with_id is my db query, I'm using when I'm using the form for updating data.
Scenario
The scenario is: I'm taking user choice first to load related div. And I don't want any collision among these three types. I put a checker for the mandatory fields before inserting or updating data (those are irrelevant for my problem so I skipped them here). Suppose I choose Type1 on the select box and the div for Type1 loads, where I forget to put some texts, and clicked the submit button, the form will reload with an error - "Mandatory fields are empty". Just now as the value of $_POST['choice_type'] == 'type1', so I want the dropdown to be selected on "Type1" option and "Type2" and "Type3" to be disabled="disabled". And with the code I presented here does the same for me. So that in the middle I can't switch the type. That's what exactly I's wanting.
PROBLEM
Now the problem is, what my JS is:
$(function() {
$('#choice_type').change(function(){
$('.togglediv').hide();
$('#' + $(this).val()).show();
});
});
with change() it did load the respective div only when I's selecting an option (that triggers a change to jQuery). As the form comes back with a selected option it doesn't load the respective div because no such change being triggered. As the other two options are now disabled according to my scenario, if I choose the "Select One" option and then choose again the "Type1" option it triggers a change to the JS and loads the div.
Question
So, how can the same JS be helpful with some simple tweaking that loads the respective div on change as well as on load or something...?
Any help would be greatly appreciated.
EDIT
With this solution in mind, I changed my jQuery into:
$(function() {
$('#choice_type').change(function(){
$('.togglediv').hide();
$('#' + $(this).val()).show();
}).focus(function(){
$('.togglediv').hide();
$('#' + $(this).val()).show();
});
});
It did a nearly good thing to my query, but it till needs to put a click on the select property. Not exactly what I's looking for.
Have you tried
<body onload="showdiv()">
with showdiv() being pretty much your above JS code? This should simply execute the function and display the correct div once the page is fully loaded.

Categories