Dropdown selector, change to target="_blank" - javascript

I have a dropdown selector in place and I need to change it so that the target="_blank" so it opens up a new tab.
Here is the current code:
<SCRIPT TYPE="text/javascript">
<!--
function dropdown(mySel)
{
var myWin, myVal;
myVal = mySel.options[mySel.selectedIndex].value;
if(myVal)
{
if(mySel.form.target)myWin = parent[mySel.form.target];
else myWin = window;
if (! myWin) return true;
myWin.location = myVal;
}
return false;
}
//-->
</SCRIPT>
<div id=countryselector>
<FORM
ACTION="../cgi-bin/redirect.pl"
METHOD=POST onSubmit="return dropdown(this.gourl)">
<SELECT NAME="gourl">
<OPTION VALUE="">Select a Country...
<OPTION VALUE="http://google.com">USA
<OPTION VALUE="http://google.ca">Canada
</SELECT>
<INPUT TYPE=SUBMIT VALUE="Go">
</FORM>
</div>
Thanks in advance

function dropdown(mySel) {
var myVal = mySel.options[mySel.selectedIndex].value;
if (myVal) {
if (mySel.form.target) {
window.open(myVal, mySel.form.target, '_attributes_');
} else {
window.location.href = myVal;
}
}
return false;
}
A list of _attributes_ can be found here for Mozilla or here for IE. There are a few differences in some of the options available, so it is best to review both lists.
You can also leave the third parameter off the function call and it should behave like target="_blank" on your <form>:
// behaves as if you submitted <form ... target="_blank">:
window.open(myVal, mySel.form.target);
Here is an example using a set of _attributes_ as documented at the links provided to open a window of a specific size and position with specific parts of the UI suppressed:
// this opens a window that is 400 pixels by 300 pixels
// it is positioned 100 pixels from the top and the left
// it will have no statusbar, no menu but the new window will have a toolbar:
window.open(myVal, mySel.form.target,
'height=300,width=400,top=100,left=100,statusbar=0,menu=0,toolbar=1');

Related

How input visible from select value when returning from another page

When selecting 1_preduzece, the input field my_field is displayed, however, when data is entered into this input and the user switches to another html page, in case he returns to the page this input field disappears but 1_preduzece remains selected. How to keep this input visible when returning from another page if 1_preduzece is selected.
<select required="" aria-required="true" name="svojina" id="svojina" onchange="showMessage(); showDiv(this)">
<option value="" disabled selected>Odaberi:</option>
<option value="1_preduzece">Korisnik 1</option>
<option value="2_preduzece">Korisnik 2</option>
</select>
<p id="vrsta"></p>
<script>
function showMessage() {
var x = document.getElementById("svojina").value;
document.getElementById("vrsta").innerHTML = "";
if (x == "1_preduzece") {
document.getElementById("vrsta").innerHTML = "";
}
if (x == "2_preduzece") {
document.getElementById("vrsta").innerHTML = "";
}
}
</script>
<div id="hidden_div" style="display: none;">
<input id="my_field" type="text" name="my" maxlength="5" size="30" disabled="true" onkeyup="saveValue(this);">
</div>
<script>
// input to track
let field = document.getElementById("my_field");
if (sessionStorage.getItem("autosave")) {
// Restore a content of the input
field.value = sessionStorage.getItem("autosave");
}
// Listen for changes in the input field
field.addEventListener("change", function() {
// save value into sessionStorage object
sessionStorage.setItem("autosave", field.value);
});
</script>
<script type="text/javascript">
function showDiv(select){
if(select.value=="1_preduzece"){
document.getElementById('hidden_div').style.display = "block";
document.getElementById('my_field').disabled = false;
} else {
document.getElementById('hidden_div').style.display = "none";
document.getElementById('my_field').disabled = true;
}
}
</script>
What you're seeing is a browser cache of sorts. The best way to circumvent that is to run a javascript function on page init to reset your form values.
In vanilla JS:
window.addEventListener('DOMContentLoaded', () => {
document.querySelector('select[name=svojina]').value='';
})
In JQuery
$(function() {
$('select[name=svojina]').val('');
})

Replace CSS line with PHP Conditional

I'm looking to replace a css line when a certain condition is met. I have a bunch of data that appears when I press Ok. Depending on what is selected in a combo-box I want the text to be red or black. I tried in javascript but it isn't working.
EDIT: I managed to change to red when I press OK, though because it reloads the data it returns to original black.
time.css
.time-title {
width:auto;
color:black;
position:absolute;
z-index:5;
}
index.php - part of it
<label> Visualizar: </label>
<select id="estado">
<option value="Normal"> Normal </option>
<option value="Crítico"> Crítico </option>
</select>
<label id="okbt">Ok</label>
</div>
<div id='placement'></div>
<script type='text/javascript'>
$("#okbt").on("click", function(){
var v1 = $("#cproc").val();
var v2 = $("#estado").val();
var tg1 = {};
var doc_ht = $(document).height();
$("#placement").css({"height":"510px"});
$(function () {
if (v2 === "Crítico") {
$(".time-title").css({"color":"red"});}
tg1 = $("#placement").timeline({
"min_zoom":1,
"max_zoom":30,
"image_lane_height":100,
"icon_folder":"timeglider/icons/",
"data_source":"pptimeline.php?ty="+v1+"&est="+v2, //add select value to url
"constrain_to_data":false
});
tg_actor = tg1.data("timeline");
var tg1_actor = tg1.data("timeline");
window.setTimeout(function() {
tg1_actor.refresh();
}, 1000);
});
});
</script>
Your JavaScript is most-likely being executed before the DOM is ready.
Try wrapping the code within a document.ready function:
<script type='text/javascript'>
$(document).ready(function() {
var v3 = $("#estado").val();
if (v3 === "Crítico")
{
$(".time-title").css({"color":"red"});
}
});
</script>

link to selection of option selected

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');
});

Receiving multiple alert messages from jsTree search

I have built the function below to search for text in jsTree.
If the search text is found, hightlight the node. If not found, alert user with "No node with the search string, try again" string.
What happens is when I put a search text that is not in jsTree, I get the alert. I search again with a valid text for the nodes but I still get the alert on the browser window.
Any ideas?
<script type="text/javascript">
function myFunction()
{
$(document).ready(function(){
var value=document.getElementById("search_field").value;
var searchResult;
var AlertsOn = false
$("#search_tree").click(function () {
searchResult=$("#tree").jstree("search",value);
if ($(searchResult).find('.jstree-search').length == 0)
{
AlertsOn = true;
}
else
{
AlertsOn = false;
}
if(AlertsOn == true){
alert($(searchResult).find('.jstree-search').length);
}
});
document.getElementById("search_field").value='';
});
}
</script>
html:
<fieldset id="search">
<input type="text" name="search_field" id="search_field" value="" />
<button id="search_tree" onclick="myFunction()"> Search</button>
</fieldset>
I can do this call in jquery to reload the page to re-initialize the alert box:
location.reload();

Adding select menu default value via JS?

i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.
I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>
You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>
You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}
if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">

Categories