user3378165 user3378165 - 9 days ago 7
jQuery Question

How to set a Select value based on <a> click

I have a MVC View with a few images, each image has a link that links to a Form that is located on the bottom of the View, the Form has a

<select>
filed that has to be populated based on the clicked link.

This is the
div
on the top of the page with the images and the links:

<div class="propImg"><img src="images/1.jpg" alt="" /></div>
<a href="#lnkForm" class="serviceRequest">Customer Service Request</a>
</div>
<div class="propImg"><img src="images/2.jpg" alt="" /></div>
<a href="#lnkForm" class="serviceRequest">Customer Service Request</a>
</div>


And this is the
form
in the bottom of the page:

<form id="formProperties">
<select id="properties" name="properties" class="required simple-dropdown txtbox">
<option value="">Select a Property</option>
<option value="1">100 Central Avenue</option>
<option value="2">220 Central Avenue</option>
</select>
</form>


This is the JavaScript function that on
<a>
click toggles the page and takes the user to the
form
:

$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {

var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});


I'm not sure how to populate the
<select>
based on the link that the user clicks.
For example: If the user clicked on the first link the
<select>
should now has the
1
value, if the second
<a>
- the
<select>
should be set with
2
etc...

Any advice?

The divs of the images and the links look like that: (I removed some design elements to shorten it but I see it is necessary...)

<div>
<div class="propImg"><img src="images/1-test-RoadL.jpg" alt="" /></div>
<span class="txt15">
<br>
<strong>1 test Road</strong><br>
Piscataway, NJ
</span>
<span class="state">
<br>
12,477 SF<br>
</span><br>
<a href="#lnkForm" class="serviceRequest">Customer Service Request</a>
</div>

Answer

Try this.

$('.serviceRequest').on('click',function (e) {
    var q = $(this);
    var target = q.index('.serviceRequest')+1;
    $("#properties option[value="+target+"]").prop("selected","selected");
    e.preventDefault();
});

And the example here : https://jsfiddle.net/synz/3s5jgr1o/1/