How to pass dropdownlist Id as parameter to javascript function? - javascript

On the client side I need to call javascript function "changeSchool" with selector's Id as parameter, as soon user selects new option (school in this case). How to pass selector's Id to such javascript function?
Table in the view contains following drop down lists:
#{
for (var i = 0; i < Model.StudentApplications.Count(); i++)
{
<tr>
...
<td>#Html.DropDownListFor(m => m.StudentApplications[i].SchoolId, Model.StudentApplications[i].SchoolList, new { onchange = "changeSchool(?);" })</td>
...
</tr>
}
}
EDIT:
From the source code I can see that ids is generated: id="StudentApplications_0__SchoolId",
id="StudentApplications_1__SchoolId", ...
etc.

Perhaps?
onchange = "changeSchool(" + Model.StudentApplications[i].SchoolId + ");"

Related

Need to pass an HTML ID for an image into a variable in javascript to use in various functions

I am trying to use code from html into javascript using code from https://www.geeksforgeeks.org/how-to-get-the-id-of-the-clicked-button-using-javascript-jquery/.
I am creating a memory game I have the images stored in an array and am able to click on it and it flips. I want to take the ID of 2 images and compare them but I need to pass the clicked ID variable from html into a javascript variable to store them for processing:
Here is my code for the detectClick function
**function detectClick(clicked) {
htmlID = clicked;
return htmlID;}**
Here is my HTML sample of my table of the first 4 array elements:
***<tr class ="success" >
<td onClick="changeimage('tblArr0',tblArr[0]);"><img src='memImages/CardBack.png' id="tblArr0"
onClick="document.getElementById('tblArr0').src='tblArr[0];detectClick(this.id);';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr1',tblArr[1]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr1"
onClick="document.getElementById('tblArr1').src='tblArr[1]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr2',tblArr[2]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr2"
onClick="document.getElementById('tblArr2').src='tblArr[2]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr3',tblArr[3]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr3"
onClick="document.getElementById('tblArr3').src='tblArr[3]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
</tr>***
I need to pass the detectClick(this.id) into the variable htmlID.
Any other ways of doing this or suggestions would help.
I have the the tblArr[] which contains another array called imgArr which stores the source name of the files for the images. I am able to have my array shuffled, now I need to be able to process the array objects to compare them. I just need to know how to get the ID from the image back into a javascript variable.
Thanks for suggestions and help in Advance!!
This should create your <td>s for as many as are available in the array:
function detectClick(clicked) {
htmlID = clicked;
return htmlID;
}
function loadSuccess() {
let container = document.getElementById("success");
for (let i = 0; i < tblArr.length; i++) {
let new_td = document.createElement("td");
new_td.setAttribute("onClick", "changeimage('tblArr" + i + "',tblArr[" + i + "]);");
container.appendChild(new_td);
let new_img = document.createElement("img");
new_img.src = "memImages/CardBack.png";
new_img.id = "tblArr" + i;
new_img.setAttribute("onClick", "this.src='tblArr[" + i + "];detectClick(this.id);';");
new_img.setAttribute("draggable", "true");
new_img.setAttribute("ondragstart", "dragstart_handler(event)");
new_el.appendChild(new_img);
}
}
<tr class ="success" id="success" onload="loadSuccess()"></tr>

Url.Action call Javascript Function

I have an Url Action Link that sends to my controller 1 paramater, but I need that paramater to call a javascript function to get document.getElementById and send that value to my controller. In my view I have the follwoing code:
#foreach (var item in ViewBag.PersonsContacts as List<Software___FPPD.Models.Contact>)
{
<tr>
<td>#Html.DisplayFor(model => item.ContactType.Name)</td>
<td>#Html.EditorFor(model => item.ContactValue, new { htmlAttributes = new { #class = "form-control", id = "contactValue"} })</td>
<td>
Alterar
</td>
</tr>
}
My javascript:
function getValue(contactValue) {
document.getElementById("contactValue").value = contactValue;
}
What I'm I doing wrong because I can not get this to work.
Url.Action is a method which gets executed in the server by razor and your javascript executes on the client side. So it is not that easy to mix both.
I am not sure what you are trying to do. In your question you mentioned you want to set value to some form field. But since you are going to be redirected to the new page, there is no point ! whatever value you set is gone (unless you are opening the new page in a new tab)
Anyway, What you can do is to listen for the click event of the anchor tag in your javascript and do whatever you want at the client side (ex: setting some form field value /executing a javascript function etc).
You have some problem in your view code, you are creating the same id value for each item in the loop in #Html.EditorFor(model => item.ContactValue .Duplicate id's are not valid. So avoid that.
<td>
#Html.EditorFor(model => item.ContactValue,
new { htmlAttributes = new { #class = "form-control myContactVal"} })
</td>
<td>
<a href="#Url.Action("SignUp", "Home")" data-contactvalue="#item.ContactValue"
class="btn btn-success myEdit"> Alterar</a>
</td>
I added 2 new css classes , myContactVal and myEdit to the form fields to help us do our jQuery selection. We are setting the item.ContactValue value in html5 data attribute to the anchor tag for accessing later in our javascript code.
And the javascript to handle the link click event
$(function () {
$("a.myEdit").click(function (e) {
e.preventDefault();
_this = $(this);
var contactVal = _this.data("contactvalue");
var url = _this.attr("href");
url = url + "?contactValue=" + contactVal;
alert(url);
//You can do any other thing here.
//If you want to update the field with myContactVal class in prev td
_this.closest("tr").find(".myContactVal").val(contactVal);
// finally do the redirect
window.location.href=url;
})
})

Get KendoUI Combobox id

I need to use the same function for the change event in KendoComboBox.
No problems in binding the Javascript function with the Combobox.
Now I need to access the name or the id of the combobox inside the change handler.
How can I do this?
This is my code:
#for (int i = 0; i < (ViewData["alertLevels"] as List<AlertLevel>).Count; i++)
{
AlertLevel lv = (ViewData["alertLevels"] as List<AlertLevel>)[i];
<div class="col-md-2">
#Html.HiddenFor(m=>m[i].contactTypeId)
<strong>#lv.descrizione</strong><br />
#(Html.Kendo().ComboBoxFor(m=>m[i].contactTypeId)
.BindTo(ViewData["contactTypes"] as SelectList)
.Name("cbxContactType["+i+"]")
.SelectedIndex(0)
.Events(
ev=>ev.Change("cbxContactTypeChange")
)
)
</div>
}
I need to access the caller combobox id in the cbxContactTypeChange function.
Assuming you are using the combobox change event: http://docs.telerik.com/KENDO-UI/api/javascript/ui/combobox#events-change
You can get the ID like this:
this.element.context.id
DEMO

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

Get Id of table row if it is checked?

I have a datatable containing a list of Cars. each row in the html contains a Car ID. I have added checkbox column to the first cell in my datatable - if it is checked the row is highligted to indicate to the user they have selected that row. What I waht to do is get all the IDs of all the cars a user has selected on clicking a button on the page. (also there are other columns in the table row where I have checkboxes (i.e - a Manual column or an Automatic column which will somtime be checked - like in column 5 ot 6 in the table)
so this is part of the cshtml for my page..
#foreach (var car in Model.Cars)
{
<tr carId="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
//more stuff set in other tds in table
Then this is the JS I have for the page so far.
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
carsListTable.find("tr").each(function (index, para) {
$('tr').find('td:input:checked:first').each(function () {
var car= new Object();
alert($(this).parent().parent().attr("carId"));
car.ID = $(this).parent().parent().attr("carId");
cars.push(car);
});
});
var jsonString = $.toJSON(cars);
I want to then return the json string to my controller (I do this by passing the value into a hidden field on my model and then deserialize - but at the minute I am getting it as empty. My problem is getting the best way to get the id from the row if it is checked?
You can use the selectors :checkbox:checked and use the jQuery.map to convert the array. The jQuery.closest() method will give the closest ancestor matching the given selector.
var cars = carsListTable.find('.table-data :checkbox:checked').map(function(i, v){
return {
ID : $(v).closest('tr').attr('carId')
}
});
Demo Fiddle
Note: The id of elements should be unique in a document so the id of the checkbox should be removed or has to be suffixed or prefixed by a dynamic value like the car id.
First, you should use class instead id for elements that will be present more than once. I suggest change #SelectIndividual for .SelectIndividual on the checkbox input). Another thing you should change is the carId attribute, because is not semantic valid. You should use custom data attributes instead. This is how your code should look like:
HTML
#foreach (var car in Model.Cars)
{
<tr data-carID="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
Jquery
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
$('SelectIndividual:checked').each(function () {
var car= new Object();
car.ID = $(this).parent().parent().data('carID');
cars.push(car);
});
});
//keep doing things
I would suggest to use the data-* attributes that are valid HTML5 as well as the jQuery.data() methods for the id of the car.
Can you assign a class to all checkboxes in first column and then try this
$('.cbClass:checked').each(function () {
tr = $(this).closest('tr');
// use the row
})

Categories

Resources