link to selection of option selected - javascript

I have a form in contact page and three links suppose one, two, and three are in home page and I would like to link to contact page for each link but with one option is to be selected one and with two option is to be selected two and so on.
<select id="message_type" name="message_type" class="inputbox">
<option value="one">Suggestion</option>
<option value="two">Inquiry</option>
<option value="three">Offer</option>
</select>
when link one is clicked the contact page should show option selected one and the like.
How can I do that?
Edit
I have three links in home page
one
two
three
Now I want to show the contact page with option selected one for link one and so on...
here is the code which results the select
<?php
function dropdown($active){
$dropdown=array(
'option1'=>'Suggestion','option2'=>'Inquiry','option3'=>'Offers'
);
foreach($dropdown as $key=>$val){
$array[]=JHtml::_('select.option',$val,$key);
}
$dropdown = JHtml::_('select.genericlist',$array,'message_type','class="inputbox"','text','value',$active);
return $dropdown;
}
?>
and in the form
<form name="feedback" id="frmfeedback" action="" method="post" >
<div>
<label for="msg">Message Type: </label><span class="input"><?php echo dropdown(isset($post['message_type'])?$post['message_type']:'');?> </span>
</div>
.......

Can put a hash in the links on home page:
Make a Suggestion
Then on contact page:
$(function(){
var opts=['one','two','three'];
var hash =location.hash;// use browser location object to get hash
if(hash && hash !='#'){
hash= hash.replace('#','');
/* get index of hash from array*/
var optIndex= $.inArray(hash,opts);
/* if not in array value will be empty string, otherwise value of hash*/
$('#message_type').val( optIndx !=-1 ? hash : '' );
}
});
EDIT: If ID's are same as values on the links as shown in question
Can append the hashes to href on home page with:
$('#one,#two,#three').attr('href',function(idx, oldHref){
return oldHref +'#' + this.id;
});
EDIT: Using itemId in query string of url:
$(function(){
var opts=['477','478','479']; /* not sure these are accurate*/
var a = document.createElement('a');
a.href = location.href;
var ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length,
i = 0,
s;
for (; i < len; i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split('=');
ret[s[0]] = s[1];
}
var currVal=ret['itemId'];
if( currVal !=undefined && $.inArray(currVal,opts)>-i){
$('#message_type').val( currVal);
}
})

For different pages
var url= document.URL;
switch(url)
{
case 'http://jsfiddle.net/bs8dp/':
$('#message_type').val('one');
break;
case 'http://jsfiddle.net/bs66p/':
$('#message_type').val('one');
break;
default:
$('#message_type').val('two');
}
jsfiddle
OR
If you have options in same page then
('#your_tab_one').click(function(){
$('#message_type').val('one');
});
('#your_tab_two').click(function(){
$('#message_type').val('two');
});
('#your_tab_three').click(function(){
$('#message_type').val('three');
});

Related

html with many similar selects that react when changed

My html contains many similar selects which I thought I could do all as
<form name="form">
<select name="site" size="1" onChange="formHandler()">
<option value="$site?i=$i&j=$2">ABC</option>
...
</select>
</form>
Contained in the html header is
function formHandler() {
var URL = "";
URL = document.form.site.options[document.form.site.selectedIndex].value;
if ( (URL != "") && (URL != "0") ) {
window.location.href = URL;
}
}
But I get TypeError: document.form.site is undefined. I presume this is because the forms and their selects all have the same name. This is because I only want one formHandler() in the header.
Very thankful for help!
Pass the element as parameter to the handler function:
onchange="formHandler(this)"
and then in the handler:
function formHandler(el) {
var url = el.options[el.selectedIndex].value;
// and the rest...
}

Need a way to get an attr from one of many of the same elements

I'm trying to access the id of an element, and slice off the num to piece together a url for an ajax call. I'm mainly using JQuery.
I have experimented with .attr() and .data() and found that they only return the first match, so everytime it would 1, no matter if I clicked on 1, 4, or 54.
.get() only returns the HTML header object, and I haven't yet found a way to access that and possibly pull out an id num.
The code:
$('.display').click(function(event) {
event.preventDefault();
//get category from h4's parent div
let $parent = $('h4').parent();
let $cat = $parent.attr('class');
let cat = String($cat);
//get id to search for...currently only returning id_1, not unique id
let $id = $('h4').get(); //need correct method here
console.log($id);
//slice off num to use in ajax url req
if($id.length == 4) {
id_num = $id.slice(-1) + '/';
} else if ($id.length == 5) {
id_num = $id.slice(-2) + '/';
} else {
id_num = $id.slice(-3) + '/';
}
console.log(id_num);
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/' + $cat + id_num,
success: function(result) {
console.log(result);
}
})
<div class="container">
<h3 id="title">I made the Kessel Run in 12 parsecs.</h3>
<form id ="searchParams" method="POST">
Now, I want to know about the
<input list="cats" name="cats">
<datalist id="cats">
<option id="people" value="people"></option>
<option id="planets" value="planets"></option>
<option id="films" value="films"></option>
<option id="species" value="species"></option>
<option id="vehicles" value="vehicles"></option>
<option id="starships" value="starships"></option>
</datalist>
in Star Wars.
<input id="getInfo" type="submit">
</form>
<div class="display"></div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/twelveparsecs.js"></script>
</body>
</html>
Thank you!
your javascript can't be right to the html snippet, it starts with failures on line 2
let $parent = $('h4').parent();
// never matches on your code, you have no h4 tag
let $cat = $parent.attr('class');
// attr is no function of undefined, null pointer exception
the way to a id can be this this;
<div id="test">
<script>
console.log($('div').attr('id'));
</script>
if a tag is given more than 1 time you will get back a array of JQuery object matching on the nodes with the $('div') selector:
<div id="1">a</div>
<div id="2">b</div>
<script>
let listOfElements = $('div');
for(var i = 0; i < listOfElements.length; i++) {
var singleElementInList = $(listOfElements[i]);
var id = singleElementInList.attr('id');
console.log(id);
}
</script>
the get command is a ajax call to read a response of a url fast

Conditional drop down menu in javascript, problems with the selector

I have a conditional dropdown menu which works but it depends on where I put it on the page. If I don't put it in a specific position the positions in the menu don't fill at all. The problem is also that I want to add a second conditional dropdown, and that one doesn't work regardless of where I put it. So my question is: do I need to add the script twice on the page to correspond the two forms I have? I actually want both drop downs to fill with the exact same words.
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
I'm guessing it's something related with the [0] there. I tried adding an id to the form and then writing the the second script document.forms('myId')[] but that didn't work either. How should I go about doing this?
<script type="text/javascript">
var categories = [];
categories["startList"] = ["Programming","Science","History","Business and Economics","Software","Languages","Do it Yourself","Others"];
categories["Programming"] = ["Java","C++","C.","Python","Html","Php","Mysql","ObjectiveC","Android","Others"];
categories["Science"] = ["Mathematics","Physics","Biology","Chemistry","Medicine","Astronomy","Statistics","Others"];
categories["Others"] = ["All"]
var nLists = 2; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[0]['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<form action="" method="post">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Category</option>
</select>
<select name='List2' onchange="getValue(this.value,this.form['List1'].value)">
<option selected >Subcategory</option>
</select>
<input type="Submit">
Fixed it. I just had to add either a selector or 1 there to correspond to my second form.
document.forms[1]['List'+i].length = 1;
document.forms[1]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[1]['List1'])

How might javascript to update dropdown options conflict with CakePHP's save?

This code causes my save to either flash "404 not found" when in a modal dialog or goes to a blank white page when in a separate tab.
Heres the code:
<script>
function changeSelection()
{
var value = $('#typeSelect').val();
var div = document.getElementById('sigType');
if(value >= 1 && value <= 3)
{
var signalTypeOptions =
<?php echo json_encode( array_values( $signalTypeOptions));?>;
var selection = document.getElementById('valueSelect');
selection.innerHTML = '';
var i = 0;
for(optionText in signalTypeOptions[value])
{
var option = document.createElement('option');
option.innerHTML = optionText;
selection.appendChild(option);
}
$(div).show();
}
else
{
$(div).hide();
}
}
</script>
The code is used to update the dropdown options for a secondary select element (valueSelect) based off of an initial select element (typeSelect).
I found that when a value is selected in the dynamically populated dropdown, the html doesn't reflect the selection.

Append multiple dropdown values to URL

I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.

Categories