Reference external option values or functions - javascript

In my code an onclick event of a link selects a drop-down option:
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#aaa", function(){
$("select").val("aaa").change();
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#bbb", function(){
$("select").val("bbb").change();
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#ccc", function(){
$("select").val("ccc").change();
});
});
</script>
</head>
<body>
<p><a id="aaa">Select Option 1</a></p>
<p><a id="bbb">Select Option 2</a></p>
<p><a id="ccc">Select Option 3</a></p>
<select>
<option>Select</option>
<option value="aaa">Option 1</option>
<option value="bbb">Option 2</option>
<option value="ccc">Option 3</option>
</select>
</body>
</html>
Issue:
I am trying to add a link to an external page that navigates to the page with the above code and automatically selects e.g. Option 2
In a sense I am trying to execute e.g. the following function
function() $("select").val("bbb").change();});
when clicking on a particular (external) link that navigates to the page of the function first.

You're going to have to send some sort of parameter to the second page that that page can read. The simplest thing would be to add a query string onto the link, like this:
Page 2
And then on "page2.html", you'll need to read the query string and act accordingly:
// This is the code that would be on page2.html
document.addEventListener("DOMContentLoaded", function(){
// Assume that the current page was arrived at with the URL: http://someDomain.com/page2.html?option=2
// That is the string that will be in window.location.href
//var theQueryString = window.location.href;
// For testing purposes we'll use it as a variable:
var theQueryString = "http://someDomain.com/page2.html?option=2".split("?")[1];
var optionNumber = theQueryString.split("=")[1];
console.log(theQueryString, optionNumber);
if(optionNumber === "2"){
// You can do whatever you need to do now that you know what the parameter
// was that was passed from the first page:
document.getElementById("foo").selectedIndex = optionNumber - 1;
doSomethingAwesome();
}
function doSomethingAwesome(){ alert("You Did It!"); }
});
<select id="foo">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>

There are a lot of different ways to solve this problem. The recommended way assumes you have access to/control over the backend server to this page, where you could load some variable into the model when a certain URL parameter is passed (i.e. ?selection=2) and when that variable is preset in the model, you can set the default parameter on the select element.
However, in the event where you only have control over the front end, you can check the URL params or the hash using document.location and subsequently make a decision from there.
For example, make the link on the external page be something like http://www.myurl.com/mypage#option2. Then in your <script> tag, you can check document.location.hash for the value option2 and then call the appropriate jQuery function to change the select element.

Related

.load jquery send double values

When I try to load the first .load it passes 1 variable without any problem, I receive this variable from a _GET method to store it in a data-id button attribute to pass it back to another .load, in this second file I receive the variable again in a _GET method and the code does its thing, but when doing the process again from the beginning, in the second .load the variable is duplicated and the alert() script shows 2 times, as well as the process of this same file too.
I have tried with .empty() and .remove() functions, likewise I have tried to load from the last .load the first file that filters the main file, but the problem still occurs.
(The main to send variable to first file in .load)
<p>Select a category</p>
<select name="category" id="category" class="form-control" required>
<option disabled selected value>category</option>
<option value="1">all cat</option>
</select>
<div id="table-category" name="table-category"></div>
$("#consult").click(function(e){
e.preventDefault();
idCategory = $('#category').val();
$('#table-category').load('../public/tabla-proyectos.php?v1='+idCategory );
});
The second .load in that id="table-category"
$category = $_GET['v1'];
<script>
alert(<?php echo $category;?>); <!-- In this part dont have problems with the variable because return only one result -->
</script>
<button id="admin" name="admin" data-id="<?php echo $category;?>">Show</button>
<div id="map"></div>
<script>
$(document).on("click", "#admin", function () { <!-- I think there's the problem -->
category = $(this).data('id');
$('#map').load('../public/mapa.php?val1='+category);
});
</script>
Final .load file
$categoy_id = $_GET['val1'];
<script>
alert(<?php echo $category_id;?>); <!-- The first time OK, but trying again from the beginning repeat the process 2 times -->
</script>
I have solved it in the following way:
I have taken the script of the second file and I have put it in the main file, adding to it an .empty() function so that it cleans all its values ​​before returning to show a new result inside this div, I have also added a new script inside the last .load file being the following:
Main file now see like:
$("#consult").click(function(e){
e.preventDefault();
idCategory = $('#category').val();
$('#table-category').load('../public/tabla-proyectos.php?v1='+idCategory );
});
$(document).on("click", "#admin", function () {
$('#map').empty();
category = $(this).data('id');
$('#map').load('../public/mapa.php?val1='+category);
});
The second file .load don't have script because now is on the main
The last file script now see like:
idCategory = $('#category').val();
$('#table-category').empty();
$('#table-category').load('../public/tabla-proyectos.php?
v1='+idCategory );

Store data-select value of href link in local storage and use it to select dropdown option on new page

I have some links in my navigation bar dropdown that all direct to the same page, but depending on the link that was clicked, it should select a specific select box option on this page. I decided to store the href link value in local storage and call the value when the linked page is loaded using jQuery, but I get the message "null" when the new page is loaded.
This is the html of the navigation bar dropdown links:
Jackets
Shoes
Shirts
JavaScript to store selected value in local storage:
window.onload = function() {
var linkInput = $('a[href="newpage.php"]').click(function () {
($(this).data('select'));
localStorage.setItem("storelinkInput",linkInput);
}
JavaScript in newpage.php:
window.onload = alert(localStorage.getItem("storelinkInput"));
var $select = $('#selector');
$select.val("storelinkInput");
HTML of select box in newpage.php:
<form>
<select id="selector">
<option value="option1">Jackets</option>
<option value="option2">Shoes</option>
<option value="option3">Shirts</option>
</select>
</form>
Honestly I am not sure if it is the best solution to use local storage for this purpose, or if it would be better to use PHP for this. Any suggestions that would point me in the right direction are much appreciated!
Thanks to Lars' comment I could fix the code and now it is running. In case someone is looking for a solution to this or a similar question here is the functional code:
This is the html of the navigation bar dropdown links:
Jackets
Shoes
Shirts
JavaScript to store selected value in local storage:
$(document).ready(function(){
$('a[href="newpage.php"]').click(
function () {
var toStore = $(this).data('select');
localStorage.setItem("storelinkInput", toStore);
});
});
HTML of select box in newpage.php:
<form>
<select id="selector">
<option value="option1">Jackets</option>
<option value="option2">Shoes</option>
<option value="option3">Shirts</option>
</select>
</form>
JavaScript in newpage.php:
$('#selector').val(localStorage.getItem("storelinkInput"));
It is important to place the second javascript ("$('#selector').val...") after the select box in the html/PHP file.

MVC select model's data from javascript

I am passing a model IEnumerable to a view. Appending the model to a dropdownlist
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<p id="result"></p>
I have javascript on change I am getting value selected
<script>
$(function () {
$("#ddlOffers").change(function () {
alert(this.value);
});
});
</script>
It is retrieving the correct value Id. On selecting from the list I want grab the record details from a Model (such as Title,CreatedBy...etc) based on the selection.
How do I select the right data from the Model using value Id selected in the javascript? and should I then append the data to the p tag? Am I on the right track? Or is there a simpler solution?
Thanks for reading.
What #Html.DropDownList do is generate html like this:
<select id="ddlOffers" name="ddlOffers">
<option value="somevalue">sometext</option>
... for all your options
</select>
And if you just need the value selected, there's a shortcut in jquery:
<script>
$(function () {
$("#ddlOffers").change(function () {
alert($(this).val());
});
});
</script>
Or if you need anything other than the value, you can get the selected <option> itself by
<script>
$(function () {
$("#ddlOffers").change(function () {
console.log($(this).find("option:selected"));
console.log($("#ddlOffers option:selected")); //both of them do the same thing
});
});
</script>
suppose your model is
public class Model {
public int Id,
public string Title,
public int CreatedBy
/*Other Properties*/
}
when you put it through this statement
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
All you get on the html side and you can check the source of the HTML file is
<select>
<option value="1">Title 1</option>
<option value="2">Title 2</option>
<option value="3">Title 3</option>
<option value="4">Title 4</option>
<option value="5">Title 5</option>
</select>
So you see the problem in getting other properties is that they dont exist in the HTML page and hence cannot be directly retrieved by the javascript.
What you can do instead is put all the data you need in the html attributes in the html option element by creating it manually.
#foreach(var m in Model)
{
#m.Title
}
now when you will handle the change even the data will be available inside the HTML and hence you will be able to access it. With something like this
<script>
$(function () {
$("#ddlOffers").change(function () {
var createdBy = $(this).data('createdBy');
alert(createdBy);
});
});
</script>
Alternatively what you can do is and this approach will only help you if you want to later convert this into a big application.
after selecting the value in the javascript you send a ajax request to another action on your server with will return you all the fields you need back.
Update:-
3. You can also inject the model serializing it to JSON in the view and then whenever required accessing the info using js. For this i generally use Newtonsoft Json (install-package newtonsoft.json) then inside the view do something like this
<script>
var model = #JsonConvert.SerializeObject(Model);
</script>
The way I have approached this before is to use a form like this:
#using (Ajax.BeginForm("ActionName", "ControllerName",new AjaxOptions{HttpMethod = "POST"}))
{
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<button type="submit">Submit</button>
}
Have the form submit to a controller and dropdown's value set to your ID field and then when it posts back into the controller, get the full object based on ID

redirect on submit button depending on option

So i am writing a code with a drop down list and a submit button. It looks like this in my CaseType.jsp file :
<title>Case Type Selection</title>
<script type="text/javascript" src="CaseType.js"></script>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
</head>
<body>
<center>
Please select the case that applies
<br><br><br>
<form action="">
<select id ="caseType" name="caseType">
<option value="PromoAttr">Promotion Attribute Change</option>
<option value="PromoOrder">Promotion Approval Order Change</option>
<option value="DefAppr">Change Default Approver on Promotion</option>
<option value=""></option>
</select>
<br><button onclick="caseSelect()" align="right">Submit</button></form>
<br>Help
</form>
What I want to be able to do is click the submit button and take in the value of which option was chosen and redirect to a different JSP page depending on the button. In my search on these questions I have only found solutions using PHP pages. and window.location or document.location doesn't seem to be working for me. This is my .js file for caseType:
function caseSelect()
{
var select = document.getElementById('caseType').value;
switch(select)
{
case "PromoAttr":
//open up form for Promotion Attribute Changes
alert("Promo attr works");
document.location.href="http://localhost:8080/PDFproj/generalCase.jsp";
break;
case "PromoOrder":
//open up form for Promotion approval order change
alert("Promo order works");
document.location.href="http://localhost:8080/PDFproj/generalCase.jsp";
break;
case "DefAppr":
//open up form for Changing default approver on promotion
alert("Default Approval works");
document.location.href="http://localhost:8080/PDFproj/generalCase.jsp";
break;
default:
}
return false;
}
Right now they are all leading to a general case page because I have not yet received the details on what each case form will have to look like, so this is just a prototype. But in the end, they will all have their own separate forms that have to be filled out and submitted.
Please let me know how I can do this. I am interested in javascript or jquery answers. Thank you.
In order to take a value from one page to another, you could add that value to the url as a query string, and once you get to that page have your javascript grab that value off the url and parse it into your code. Set the parameter like so:
case "PromoAttr":
alert("Promo attr works");
var url = "http://localhost:8080/PDFproj/generalCase.jsp";
location.href = url + "?selectedVal=PromoAttr";
break;
//Repeat for other cases, substituting "PromoAttr" for the selected value.
Then in your next page you can check to see if there are any query strings attached to your url, and if there is, parse it off and use it as you wish.

Dropdown Navigation Menu Using Javascript in Wordpress

I've been working on a wordpress site for an internship and I'm wanting to embed javascript code in a page to create a dropdown menu that navigates the browser to the selected page.
I'm wondering, is there something special you need to do to allow js to work in a wp page?
I tried the following code embedded in the page using the html side of posting option:
<script language="javascript" type="text/javascript">
<!--
function menu_goto( menuform )
{
// see http://www.thesitewizard.com/archive/navigation.shtml
// for an explanation of this script and how to use it on your
// own site
var baseurl = "173.236.164.86/where-to-buy/" ;
selecteditem = menuform.newurl.selectedIndex ;
newurl = menuform.newurl.options[ selecteditem ].value ;
if (newurl.length != 0) {
top.location.href = baseurl + newurl ;
}
}
//-->
</script>
<form action="dummyvalue">
<select name="newurl" onchange="menu_goto(this.form)">
<option value="" selected="selected">----- Select A Product -----</option>
<option value="vene-prototype-version/">VENE Prototype Version</option>
<option value="configuration-vene-version/">VENE Configuration Version</option>
<option value="customized-vene-version/"> VENE Customized Version</option>
</select>
</form>
The dropdown menu appears, but fails to redirect the browser on change.
I have tried surrounding the code in the page with the tags and that has no effect either.
http://173.236.164.86/where-to-buy/
thanks for the help!
Developer Tools show a parse error in your JS. Probably from WP automatically inserting paragraph returns. Remove all the white space and carriage returns in the JS and try it.

Categories