jquery: value on $.post that depends on link selected - javascript

I have a page in my application with two hyperlinks. Both of these hyperlinks redirect the user to the same page where they can add information for a new account. When link #1 is selected, one value passed to the controller action must be 1. If the other link is chosen then the value is 2. How can this be done using jquery?
hyperlinks:
<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
ADD CLINIC
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
ADD MEDICAL OFFICE
</div>

Why on Earth do you need to use jQuery for this? Use simple GET parameters.
ADD MEDICAL OFFICE
Note the ?type=1 Passes a get parameter with a value of one.
On the recieving page you can use the folllowing function to check which get parameter was passed.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
Use like this: findGetParameter('type') to get the value of the type from the url.
Got that function from here

just add a GET parameter to the links, they will keep pointing to the same URL but also will pass a parameter
<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
ADD CLINIC
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
ADD MEDICAL OFFICE
</div>

You should define a new attribute like data-id your html element after that detect the click action and change the href.
<div>
<a href="~/rxcard/addaccount" data-id='1'>ADD CLINIC</a>
</div>
<div>
<a href="~/rxcard/addaccount" data-id='2'>ADD MEDICAL OFFICE</a>
</div>
<script>
$("a").on('click',function(){
var thiz = $(this);
thiz.attr('href',thiz.attr('href')+?val=thiz.attr('data-id'));
});
</script>
If you have value in initialization you can give different hrefs your anchors. In this scenario you don't need to Jquery or Javascript;
<div>
ADD CLINIC
</div>
<div>
ADD MEDICAL OFFICE
</div>

Related

Reloading of javascript function via JQuery .change adds variables from previous runs

I would like to change fonts dynamically, But my code only behaves nicely the first time i change a font. It seems that my code remembers previous clicked buttons and adds those to be changed as well every time i select a new font for a button. My code is available at jsfiddle
function font(id,element){
$(id).bind('change',function(){
var fontTypeSelected = $(id).val();
$(element).css('font-family',fontTypeSelected);
});
}
$('#settings-ID').change(function(){
font('#font','#' + $('#settings-ID').val());
});
$('.list').on('click','.settings',function(){
// Set current row or box section ID
$('#settings-ID').val($(this).attr('id'));
$("#settings-ID").trigger("change");
});
.list div {
float:left;
padding:10px;
background-color:#CCC;
margin:10px 10px 0 0;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on one of the buttons below to change font
<div class="list">
<div class="settings" id="1">Font one</div>
<div class="settings" id="2">Font two</div>
</div>
<br>Selected button ID: <input type="text" id="settings-ID" placeholder="None selected"><br>
<br>
<select class="form-control" id="font">
<option>Arial</option>
<option>Courier</option>
<option>Verdana</option>
<option>Times new roman</option>
</select>
I really hope someone can help me with this problem. I'm kind of stuck here.
You are defining multiple change events when you call the function
Use .unbind("change") to delete the change event before defining the next one.
function font(id,element){
$(id).unbind('change').bind('change',function(){
var fontTypeSelected = $(id).val();
$(element).css('font-family',fontTypeSelected);
});
}

Javascript - simplifying a bunch of long repetative hide/show functions

Things have gotten out of hand for me. What started off as the simplest solution has ballooned to the point where it is no longer manageable. I need to come up with a way to simplify a process.
Currently I have a map with pins denoting specific countries world-wide. As the mouse hovers over a pin, a hidden div appears. When you mouse over another one, the previous div disappears and a new one opens. I started with like 5 of these and it wasn't an issue but I keep getting requests for more and want to manage the script in a different way now.
$('#PH1').mouseenter(function () {
$('#BO2').hide();
$('#US2').hide();
$('#UK2').hide();
$('#CH2').hide();
$('#BZ2').hide();
$('#QC2').hide();
$('#OT2').hide();
$('#VA2').hide();
$('#RU2').hide();
$('#JT2').hide();
$('#HK2').hide();
$('#SH2').hide();
$('#BJ2').hide();
$('#XI2').hide();
$('#BE2').hide();
$('#AT2').hide();
$('#FR2').hide();
$('#MX2').hide();
$('#PH2').show();
});
$('#PH1').click(function (e) {
e.stopPropagation();
});
$('#mint').click(function () {
$('#PH2').hide();
});
In this instance div id #PH1 is the pin, when the mouse enters the div it hides all of the other div's #**2 and displays the one related to #PH1, which is #PH2
This list is repeated for each DIV. Every time I need to add a new DIV I need to make each existing list longer as well as create a new one. How can this process be made much simpler?
Thats not a right way to do this, you should use classes for this. But their is a wayaround for this all you need to is add a class add class ele1 to all #**1 and ele2 to all #**2:
then
$('.ele1').mouseenter(function () {
$(".ele2").hide();
var id = this.id;
var newId = id.substring(0,2)+"2";
$("#"+newId).show();
});
Make a loop:
var all= ['#BO2', '#US2', '#UK2', '#CH2', '#BZ2', '#QC2', '#OT2', '#VA2', '#RU2', '#JT2', '#HK2', '#SH2', '#BJ2', '#XI2' , '#BE2', '#AT2', '#FR2', '#MX2', '#PH2']
all.forEach(function (i){
$(i).hide();
});
Use a class selector on all of the DIVs you want to hide/show instead of an ID.
First, add a shared class to all DIVs so we target all of them by class.
HTML: class="hidden-divs"
jQuery: $('.hidden-divs').hide();
Then show the relevant DIV.
$('#PH2').show();
Using your first example, it would look like this:
$('#PH1').mouseenter(function () {
$('.hidden-divs').hide();
$('#PH2').show();
});
You can use jquery to hide multiple divs if you can select them. For example, suppose you have a common class ".map_divs" on all your divs, you could easily do:
$(".map_divs").hide();
On a side-note, you could solve all this on CSS, using :hover. For example:
.map_divs:hover {
display: block;
}
If you can edit the div's yourself (if it is not generated by a library) I would do it like this.
Add a common class to all your divs. Then on each div, add a data attribtue to the related id.
<div class="pin" id="PH1" data-rel="PH2"></div>
Then you can have a simple function like this:
$(".pin").mouseenter(function() {
var relatedId = $(this).data("rel");
$(".pin[id$='2']").hide(); // Hide all pins with id ending in 2
$("#" + relatedId).show() //show PH2
})
Using classes might be a better option here. You can then just attach the mouseenter event on document ready to all pins. This will work for an infinite number of pins too.
$('.pin').mouseenter(function () {
$('.popup').removeClass('show');
var id = this.id.split('_')[1];
$('#popup_' + id).addClass('show');
});
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.popup.show {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
If your div element is ordered like below, you can get the same result using css only, which will increase speed and overall experience (especially on phones and tablets).
When "hover" the yellow squares, the popup will be visibible even when "hover" the popup.
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.pin:hover + .popup {
display:block;
}
.pin.type2 {
background-color:yellow;
}
.pin.type2:hover .popup {
display: inline-block;
margin-top: 30px;
}
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
<div id="pin_3" class="pin type2"><div id="popup_3" class="popup"></div></div>
<div id="pin_4" class="pin type2"><div id="popup_4" class="popup"></div></div>

find is not working to select data from dom in jquery

what i need
i need to access href from class events_links .
html code
<div class="row flush frt" itemscope="" itemtype="http://schema.org/Event">
<div class="12u">
<div class="evntblk">
<a itemprop="url" class="events_links" href="/dailymail-ideal-homeshow">
<h2 class="lnh1" itemprop="name">Ideal Home Show - London</h2>
</a>
<div style="display:block; float:right; width:auto; color:#7c7c7c;"></div>
<span itemprop="startDate" class="startdates" content="2015-03-20">20 Mar-06 Apr 2015</span><span itemprop="endDate" class="enddates" content="2015-04-06"></span><br><span itemprop="location" itemscope="" itemtype="http://schema.org/Place"><span itemprop="name" style="display:none">Olympia Exhibition Centre</span><span itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress"><span itemprop="addressLocality" class="eventcity">London</span>,
<span itemprop="addressCountry" class="eventcountry">UK</span></span></span>
<p class="tal" style="overflow:hidden">The ZEE Asian Pavilions are a celebration of British Asian Culture, that encapsulates Asian food, Asian fashion,...<br><span style="background: none repeat scroll 0 0 #ECECEC; border-radius: 5px; color: #333333; display: inline-block; font-size: 0.8em;line-height: 13px; margin: 5px 2px 0 0 !important; padding: 5px 8px;">Home Furnishings & Home Textiles</span></p>
</div>
<div class="row flush footer"><div class="12u"><a class="button button-blue small">View Details</a></div></div>
js code
$('.small').click(function()
{
alert("test");
window.location.href = $(this).find(".events_links").attr("href");
});
snapshot of html element
i have tried to access with .parent() but it not working.
o/p
i need to access events_links class by click on class small so that i
would get href from that html element.
any suggestion are most welcome.
Simple solution to get only the related url is with parent() function:
$('.small').click(function()
{
window.location.href = $(this).parent().parent().parent().find(".events_links").attr("href");
});
since you are three levels underneath.
find() will start searching from the given object downwards in hierarchy.
BUT as stated before, this will fail, as soon as you change your html layout and maybe drop or add a div container.
it would be much better practice to give your divs containing the urls unique id's or store the link with the data attribute of the button.
So for example if in your HTML Code you had this
<div id="link12" class="event_links" href="FOUND THIS!">
<div class="whatever">
<div class="anotherone">
<div class="button small" data-link="link12" data-href="FOUND THIS HERE TOO!">
CLICK HERE
</div>
</div>
</div>
</div>
Then your click code could access URL via 2 methods:
$('.small').click(function()
{
// METHOD 1: get by storing unique id with button
alert($('#'+$(this).attr('data-link')).attr("href"));
// METHOD 2: same effect, but shorter storing href at button
alert($(this).attr('data-href'));
});
try this
$('.small').click(function() {
alert("test");
window.location.href = $(".events_links").attr("href");
});
I would suggest data-attr in this case, where you do not want to depend on code structure and css.
<div class="row flush footer">
<div class="12u">
<a class="button button-blue small" data-relative-path="some-location">View Details</a>
</div>
</div>
And
$('.small').click(function(){
window.location.href = $(this).data('relative-path');
});
You can try this one:
$('.small').click(function() {
alert("test");
window.location.href = $(".evntblk .events_links").attr("href");
});
If you need to get only href of the single .event_links object in the current .box.panel do:
$('.small').click(function()
{
alert("test");
window.location.href = $(this).closest(".box.panel").find(".events_links").attr("href");
});
closest will get you the first parent element that matches the selector. This way if you have any other .event_links that are not into this panel, they'll be skipped. If you use parent() you'll be forced to keep the same HTML sturcture between the .small and it's parents.
First of all it's bad practice to try and load a url based on a css class. That is because it is probable you use css classes repeatedly on a single page, resulting in multiple anchor selections.
However you could do the following:
$('.small').click(function()
{
var btn = $(this);
// find the closest element of click button with class 'event-block'
// find the element with class 'events_links'
// change window location to value at href
window.location.href = btn.closest('.event-block').find('.events_links').attr("href");
});

How to have slideToggle for multiple items on one page?

Im having problems with this code to work.. http://jsfiddle.net/whitewiz/z4fpx/
HTML
<h1 id="flip">Title<h1>
<div id="panel">
<p>Description that slides down</p>
</div>
<h1 id="flip">Title<h1>
<div id="panel">
<p>description that DOESN'T slide down</p>
</div>
JavaScript
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
and CSS
#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}
They work for first description, but doesn't work for the rest. I have about 18 #panels that should slide down, when I press on "Title" but only the first works.. Could you please find the missing piece in javascript that doenst allow multiple toggle?
Example on -> http://jsfiddle.net/whitewiz/z4fpx/
The first one works because that is the first element in the DOM with that id. Generally it is bad practice to have the same id assigned to multiple elements. Instead, use classes, like this:
HTML:
<h1 class="flip">Title<h1>
<div class="panel">
<p>Description that slides down</p>
</div>
<h1 class="flip">Title<h1>
<div class="panel">
<p>description that DOESN'T slide down (but does now)</p>
</div>
CSS:
.panel,.flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
.panel
{
padding:50px;
display:none;
}
I assume you only want to expand the panel following the header that you clicked on, in which case you need to get the closest element with the class name "panel" that follows the "flip" that was clicked on.
$(document).ready(function(){
$(".flip").click(function(){
$(this).next().find(".panel").slideToggle("slow");
});
});
Working example: http://jsfiddle.net/BBQJy/
The initial question seems to be lacking proper closing tags, an error that was duplicated in Nile's answer. Therefore, it didn't work for the original poster.
Based on Anna Brila's updated jsfiddle (http://jsfiddle.net/whitewiz/WuNHz/2), a possible correct solution would be:
$(".flip").click(function(){
$flip = $(this);
$content = $flip.next();
$content.slideToggle();
});
This is predicated on the use of classes instead of ids.
Full working example: http://jsfiddle.net/wy8gq1bj/1
Note: In the example, the only HTML I changed was the removal of the <br> immediately after the third , which was keeping the last item from expanding and collapsing.

how to change a property of the first child

I am able to change the background-color of this element:
<div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
</div>
But I want to change the color of the first child, which I assumed should work like this:
<div onmouseover="this.firstChild.style.backgroundColor='blue'" onmouseout="this.firstChild.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
<div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>
</div>
But it does not work. What is wrong? How can I change the style of the firstChild?
PS: I later want to use display=block and none and some other propertys (not just style) for the child. The color was just for testing.
As "the system" mentioned, you are targeting a text node rather than an element node. Try using children[0] instead of firstChild.
jFiddle here
You would need to use .firstElementChild, or you'd need to get rid of the formatting whitespace. That whitespace becomes a text node, which is the .firstChild.
The .firstElementChild property isn't supported by some older browsers, so if you're supporting those, you'd need to shim it with a function.
<div onmouseover="changeColor(this, 'blue')" onmouseout="changeColor(this, 'red')" style="background-color:green; width:100px; height:40px;">
<div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>
</div>
function changeColor(el, color) {
firstElemChild(el).style.backgroundColor=color;
}
function firstElemChild(el) {
if (el.firstElementChild)
return el.firstElementChild;
el = el.firstChild
while (el && el.nodeType !== 1)
el = el.nextSibling;
return el;
}

Categories

Resources