Add javascript var to href - javascript

I have dropdown with different links, before that i have 2 radio buttons where you could select "mode".
<div class="radio">
<label><input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label><input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://example.com/index.php?mode=">Site1</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site2</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site3</a></li>
</ul>
</div>
And i use this code snippet to detect what mode is selcted and add it to var mode:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
});
});
What i want to do is to add javascript var $mode to href tags.
href="http://example.com/index.php?mode={$mode}
How could i accomplish this ?
I think only way would be to do this with some javascript function ?
Its not possible to just "print" var to href ?
JSFIDDLE: https://jsfiddle.net/DTcHh/18683/

Use data-* attribute to keep static href value to be used later. .change() will trigger change event initially to set the value of href attributes.
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function() {
var mode = myRadio.filter(':checked').val();
$('ul.dropdown-menu a').prop('href', function() {
return this.getAttribute('data-href') + mode;
})
}).change();
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label>
<input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://site1.com/index.php?mode=" data-href="http://site1.com/index.php?mode=">Site1</a>
</li>
<li><a target="_blank" href="http://site2.com/index.php?mode=" data-href="http://site2.com/index.php?mode=">Site2</a>
</li>
<li><a target="_blank" href="http://site3.com/index.php?mode=" data-href="http://site3.com/index.php?mode=">Site3</a>
</li>
</ul>
</div>
Fiddle here

Check this fiddle I've modified for you: https://jsfiddle.net/so2fw1o4/1/
Add this to your myRadio.on('change', function
//here change the urls
$('.dropdown-menu a').each(function(){
$(this).attr('href', $(this).data('url') + mode)
})
And you will need to add data attribute to each link to store initial link
<a target="_blank" data-url="http://site. com/index.php?mode=" href="http://site. com/index.php?mode=">Site1</a>

Try this :-
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
$("ul.dropdown-menu li a").each(function(){
$(this).attr('href',$(this).attr('href').split('?')[0] + "?mode=" + mode);
});
}).change(); //trigger on page load
});
DEMO

Although you already have some answers here, I figured I would post another alternative (not necessarily any better).
You could add a class to each link, handle their click events, and set the new window's location yourself to achieve a similar effect.
The following is a code snippet modifying the jQuery in your fiddle:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
var mode = myRadio.filter(':checked').val(); // Initial setting
myRadio.on('change', function () {
mode=myRadio.filter(':checked').val();
});
$('.mode-link').click(function(e) {
e.preventDefault(); //stop the click action
// Check if the mode has been set
if (mode) {
// Create the href value
var newHref = $(this).attr('href') + mode;
// Open the new tab/window with the correct href value
window.open(
newHref,
'_blank'
);
}
});
});
I simply added the mode-link class to each a element in the dropdown, stored the radio button value change in a new variable mode, added the click event handler, and finally handled the click event to create the new href value and open a new tab/window with that location.
If you didn't want the new tab/window you could simply set location.href = newHref but this wouldn't mimic the new tab/window opening, hence why I use window.open().
I have a modified sample here: JSFiddle

Related

Javascript click function only work once

I have a dropdown menu with a submit function that executes, if any children from the dropdown is clicked.
Now I want to prevent the submit function to a special li element, because there should be insert a tracking id in a popup iFrame.
With the following code it works so far on the first dropdown menu and prevent the submit function, but it wont work on all following dropdown's.
Maybe someone has a short solution for me?
<script type="text/javascript">
$(document).ready(function() {
$('.track').click(function(){
stopPropagation();
});
$('.dropdown li').click(function() {
document.getElementById('opt').value = $(this).data('value');
$('#options').submit();
});
$("#options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
});
</script>
<form name="" action="" method="post" id="options">
<input type="hidden" name="update" id="opt" value="">
<div id="item-select-option">
<div class="dropdown">
Options <span class="caret"></span>
<ul id="selector" class="dropdown-menu pull-right" role="menu">
<li data-value="paid">paid</li>
<li data-value="shipped">shipped</li>
<li class="track">track</li>
</ul>
</div>
</div>
</form>
Problem: You've several elements with the id track/options when the id attribute should be unique in same document, so when you attach event to the id just the first element with this id that will be attached.
Suggested solution :
Use class instead of id's, like :
<form name="" action="" method="post" class="options">
.....
<li class="track">
track
</li>
</form>
Then you js should be like :
$('.track').click(function(event){
event.stopPropagation();
});
$(".options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
NOTE : The event should be present in anonymous function function(event).
Hope this helps.

jQuery: Disable onclick event using off() not working

Here is a simple example of what I'm trying to do, I have code in HTML and my aim is to disable the three hyperlinks #validate,#organize and #export:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
When I'm trying to call the following, nothing happend. I'm using jQuery 1.11.4 and I've read that the methods for disabling event listeners have changed since 1.7. So I would like to know if there is an error in my JavaScript code below or some new changes:
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
One way would be to temporarily set the onclick to null, but store the original element onclick in the element or jquery object (e.g. data). With a helper function you can switch the elements on or off:
function setEnabled($a, Enabled ){
$a.each(function(i, a){
var en = a.onclick !== null;
if(en == Enabled)return;
if(Enabled){
a.onclick = $(a).data('orgClick');
}
else
{
$(a).data('orgClick',a.onclick);
a.onclick = null;
}
});
}
Which can be called with something like:
setEnabled($('#validate'), false);
(also works on jquery objects with multiple elements because of the each)
Example fiddle
You need to unbind the click event (which was declared inline) as follows.
document.getElementById("import").onclick = null;
document.getElementById("validate").onclick = null;
document.getElementById("organize").onclick = null;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
You could have jQuery take over your inline event, so that you can off() it later. Note that off() does remove the listener. You can't really disable it unless you put some logic in the handler itself to bail out if it shouldn't be running.
function switchScreen(screenName) {
console.log(screenName);
};
$(function() {
$('#menuitems a').each(function() {
var oldClick = this.onclick;
$(this).on('click', $.proxy(oldClick, this));
this.onclick = null;
});
$('#import').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
try unbind instead of Off since click event is defined inline, if click is attached using on then it will work with off.
Event attached through javascript doesn't recognize by jquery, so javascript and jquery mixed approached can't work properly - that's the reason jquery
.off('click'); doesn't detach click event.
Modify html:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);">IMPORT</a> >>
<a id="validate" href="javascript:void(0);">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);">EXPORT</a>
</p>
Attach click event using jquery:
$(document).ready(function () {
$('#import').on("click", function () {
switchScreen('Import');
});
$('#validate').on("click", function () {
switchScreen('Validate');
});
$('#organize').on("click", function () {
switchScreen('Organize');
});
$('#export').on("click", function () {
switchScreen('Export');
});
});
Disable click event whenever required:
$('#import').off('click');
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
The above approach works for all standard browsers but just for IE we can have one more approach:
$('#validate').attr("disabled", "disabled");
$('#organize').attr("disabled", "disabled");
$('#export').attr("disabled", "disabled");

Hide or disable drop down list menu buttons. jQuery of JavaScript.

I have a dynamically created 3 options list which are attached at the end of a table row. I want to hide or disable Edit and Copy options if certain conditions are not met when page loads. How can i do this using either jQuery of JavaScript.
<div class="btn-group ewButtonGroup open">
<button class="dropdown-toggle btn btn-small" data-toggle="dropdown" href="#">Options <b class="caret"></b></button>
<ul class="dropdown-menu ewMenu">
<li><a class="ewRowLink ewView" data-caption="View" href="teamsview.php?showdetail=&TeamID=1">View</a></li>
<li><a class="ewRowLink ewEdit" data-caption="Edit" href="teamsedit.php?TeamID=1">Edit</a></li>
<li><a class="ewRowLink ewCopy" data-caption="Copy" href="teamsadd.php?TeamID=1">Copy</a>
</li>
</ul>
</div>
I have tried the following code which deosnt work.
<script>
$(document).ready(function() {
var Week_Check = $('#ewRowLink ewView span').text();
if ( Week_Check > 10) {
$('.ewRowLink ewView').hide();
}
});
</script>
You have a bad jQuery selector. If you want to hide an element having both of those classes you want to go this way:
$('.ewRowLink.ewView').hide();
By using $('.ewRowLink ewView').hide(); you basically state: hide all ewView (?) elements that are inside other elements having ewRowLink class.
You can use .off() to unbind the event:
$('.ewEdit, .ewCopy').off('click');
or if you want to hide:
$('.ewEdit, .ewCopy').hide();
Yet you need to mention on what condition you want to do this.
<script>
$(document).ready(function() {
var Week_Check = $('#ewRowLink, #ewView').find('span').html();
if ( Week_Check > 10) {
$('.ewRowLink, .ewView').hide();
}
});
</script>

Getting data-* attribute for onclick event for an html element

<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
I want to get the data-id and data-option values inside the function goDoSomething(10, 21) I have tried to use this reference: this.data['id'] but it did not work.
How can I do this?
You can achieve this $(identifier).data('id') using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename") if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
Like this:
$(this).data('id');
$(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a element and gets the data-id attribute from it.
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at
https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
you can directly use anchor id or data-action attributes to trigger the event.
Html Code
<a id="option1" data-action="option1" data-id="10" data-option="21" href="javascript:void(0);" title="Click Here">Click Here</a>
jQuery Code:
$('a#option1').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option')) ;
});
OR
$('[data-action="option1"]').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option'));
});
User $() to get jQuery object from your link and data() to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>

Triggering multiple mailto links with jquery

I'm starting to think that this may not even be possible, but I'm trying to automate a backend management task for myself here by allowing multiple emails to be initiated at once.
I have a table with users. The last column of the table has a drop-down button with mailto links that initiate various emails to the user for that row. The column also has a checkbox next to the button. Here's a simplified snippet:
<table>
<tr>
<td>
User
</td>
<td>
<div class="btn-group individual-btn">
<a class="btn btn-default dropdown-toggle" href="#" data-toggle="dropdown">
Email User
<ul class="dropdown-menu">
<li>
<a class="no-open" href="mailto:user?subject=why&body=etc">
Why didn't you open?
</a>
<a class="no-open" href="mailto:user?subject=why&body=etc">
Why didn't you click?
</a>
<a class="no-open" href="mailto:user?subject=why&body=etc">
Why didn't you pay?
</a>
</ul>
</div>
<input type="checkbox" class="selected-row">
</td>
</tr>
<tr>
rinse and repeat...
At the end of the table I have a button with the same set of actions but the idea for this button is that clicking it will open an email for every selected user (as indicated by the checkbox).
<div class="btn-group master-btn">
<a class="btn btn-default dropdown-toggle" href="#" data-toggle="dropdown">
Email All Checked Users
<ul class="dropdown-menu">
<li class="email-items">
<a class="no-open" href="#">
Why didn't you open?
</a>
<a class="no-open" href="#">
Why didn't you click?
</a>
<a class="no-open" href="#">
Why didn't you pay?
</a>
</ul>
</div>
I thought the js might be this easy:
$(".master-btn .email-items a").click(function(e){
linkClass = "a." + $(this).attr("class").trim()
$(".selected-row:checked").prev(".individual-btn").find(linkClass)[0].click();
e.preventDefault();
});
But that only opened an email for the first selected row. So, I thought, well maybe the dom needs space between these clicks, so I'll iterate over each and put a delay in to simulate clicks; but same result: only the first selected row is emailed:
$(".master-btn .email-items a").click(function(e){
linkClass = "a." + $(this).attr("class").trim()
$(".selected-row:checked").each(function(i){
var self = this
setTimeout(function(){
$(self).prev(".individual-btn").find(linkClass)[0].click();
}, 2000*i);
});
e.preventDefault();
});
Any thoughts? Will the browser even allow this?
Working example: https://jsfiddle.net/gaboom/h81qov5g/
$("#send").on("click", function(event) {
event.preventDefault();
$("#iframes").empty();
$("#links a").each(function() {
setTimeout($.proxy(function() {
var popup = window.open($(this).attr("href"))
setTimeout($.proxy(function() {
this.close();
}, popup), 100);
}, this), 100)
})
})
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="send" href="#">CLICK TO SEND</a>
<div id="links" class="hidden">
John
Sarah
John
Sarah
John
Sarah
</div>
I think this is the fix:
$(".selected-row:checked").prev(".individual-btn").find(linkClass).each(function() {
$(this)[0].click();
});
When you use [0] on a jQuery object, it only returns the first DOM element in the collection, equivalent to .get(0). If you want an array of all DOM elements, you would have to use .get() (with no arguments it returns all the elements).

Categories

Resources