Get KendoUI Combobox id - javascript

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

Related

Changing input box also need to find check box checked or not in JS

I have input box along with checkbox in table <td> like below,
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" id="summary" title="Check to set as Summary" />
</td>
Based on check box only the content of input box will be stored in DB.
In the JS file, I tried like
var updateComment = function( eventData )
{
var target = eventData.target;
var dbColumn = $(target).attr('data-db');
var api = $('#api').val();
var newValue = $(target).val();
var rowID = $(target).attr('data-id');
var summary = $('#summary').is(':checked');
params = { "function":"updatecomments", "id": rowID, "summary": summary };
params[dbColumn] = newValue;
jQuery.post( api, params);
};
$('.Comment').change(updateComment);
But the var summary always returning false.
I tried so many ways prop('checked'),(#summary:checked).val() all are returning false only.
How to solve this problem?
Looks like you have multiple rows of checkboxes + input fields in your table. So doing $('#summary').is(':checked') will return the value of first matching element since id in a DOM should be unique.
So, modify your code like this:
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" class="summary" title="Check to set as Summary" />
</td>
And, instead of $('#summary').is(':checked'); you can write like this:
var summary = $(target).parent().find(".summary").is(':checked');
By doing this, we are making sure that we are checking the value of checkbox with the selected input field only.
Update: For listening on both the conditions i.e. when when checking checkbox first and then typing input box and when first typing input box and then checked:
Register the change event for checkbox:
// Whenever user changes any checkbox
$(".summary").change(function() {
// Trigger the "change" event in sibling input element
$(this).parent().find(".Comment").trigger("change");
});
You have missed the jQuery function --> $
$('#summary').is(':checked')
('#summary') is a string wrapped in Parentheses. $ is an alias for the jQuery function, so $('#summary') is calling jquery with the selector as a parameter.
My experience is that attr() always works.
var chk_summary = false;
var summary = $("#summary").attr('checked');
if ( summary === 'checked') {
chk_summary = true;
}
and then use value chk_summary
Change all the occurrences of
eventData
To
event
because event object has a property named target.
And you should have to know change event fires when you leave your target element. So, if checkbox is checked first then put some text in the input text and apply a blur on it, the it will produce true.
Use like this
var summary = $('#summary').prop('checked');
The prop() method gets the property value
For more details, please visit below link.
https://stackoverflow.com/a/6170016/2240375

Create div X number of time from input

I am trying to create div using javascript and jquery.
My Code so far:
<script>
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
var newDiv = $('#server div:first').clone();
$('#server').append(newDiv);
}
</script>
<input type="text" name="numserver"><br>
<button onclick="new_server()">GO</button>
<br>
<div id="server">
<div id="1">
<table border="3"><tbody>
<tr><th colspan="4" style="background-color:#b0c4de;">Server 1</th></tr>
<br>
<tr><td>Technology<select name="tech[]"><option value="w">Web</option><option value="d">DB</option><option value="m">Mail</option><option value="o">Other</option></select><br>
<br></td>
<td>CPU? <input type="text" name="cpu[]"><br></td>
<td>Memory? <input type="text" name="memory[]"><br></td>
<td>Disk Space? <input type="text" name="space[]"><br></td></tr>
<br>
</tbody></table>
</div>
</div>
My end result is for the user to be able to enter the amount of servers and click GO and then the divs are automatically created.
I know how to get the numOfWindows value but i think it should work with a static value for now.
The code is correct, but how says adeneo, you don't have a DOM ready handler.
Use instead something like this:
function LoadMyJs(){
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
var newDiv = $('#server div:first').clone();
$('#server').append(newDiv);
}
}
<body onLoad="LoadMyJs()">
You are trying to run the script which works with undefined HTML. To solve this you can either move your script after defining HTML or use jquery shortcut document.ready function such as $(function(){<your code here>});.
In first case event handler has to be a global variable right away. Otherwise you declare this variable before shortcut scope.
Next you define that event handler function obtains input value ($('input[name="numserver"]').val()). And now you can generate as many divs as defined by the value(Array.apply(null, [+value]).map(function(){<generator here>})). To generate copies clone method may be used and generated divs should be inserted into div container as you do.
Looks like you're trying to generate divs by "GO" button click. In your case to do that event handler function should be named "new_server". And you don't call this function in "onclick" attribute you just declare it.

In asp.net razor mvc How do I utilize the selected dropdown item within a if statement, within a div?

This question is not a duplicate.
That above question, suggested to be a duplicate asked how to use the same variable between Java and asp.net.
Whereas this question accepts the previous isn't possible and is instead asking what other methodologies are possible?
In asp.net razor mvc How do I utilize the selected dropdown item within a if statement, within a div?
As you can see from the code below, I created a dropdown and filled it with data.
I want the selected item to be utilized in the below div.
When the user clicks on an item, what is contained within that div is revealed
Then the selected string item is used within the if statement within the div
What currently happens is, the selected item isn't globally accessible, causing the issues you can see below.
But as I've been told by knowledgable others, you can't utilise the same variable between javascript and asp.net mvc razor. So the below will not work.
How can this be accomplished? (utilization of the selected dropdown item within a if statement, within a div?)
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="display-field" align="left">
<select name="mydropdown" id="mydropdown" onchange="onChange()">
#foreach (var lLMMI in lIM)
{
<option value="#lLMMI.Key.Product.PCode">
#locItem.Key.Loc.N (#lLMMI.Key.Loc.Code)
</option>
}
</select>
<br /><br />
</div>
}
var itemselected = "";
<div>
<script>
function onChange() {
var item = document.getElementById("mydropdown").value;
$('#summary').show();
}
</script>
<div id="summary">
#foreach (var lLMMI in lIM)
{
if (#lLMMI.Key.Pro.PCode == itemselected.toString())
{
<summary>extra html elements are added etc.</summary>
}
}
You should use only javaScript. Update your code as follows:
<script>
var serverCode = "#lLMMI.Key.Pro.PCode"; // get the server value on JS
function onChange() {
var localCode = $("#mydropdown").val();
if(localCode == serverCode)
$("#extrasummary").show();
$('#summary').show();
}
</script>
<div id="summary">
<div id="extrasummary" style="display:none">extra html elements are added etc.</div>
....
</div>
Handle the change event of your dropdown and make an ajax call to return a partial view that you can add to the DOM using jquery .load(). Note in your view remove the #foreach so you just have
<div id="summary"></div>
which is where the returned html will be displayed
Script
$('#mydropdown').change(function() {
var selectedID = $(this).val();
var url = '#Url.Action("Details", "YourController")';
$('#summary').load(url, { ID: selectedID });
});
Controller
public ActionResult Details(int ID)
{
var model = // Get the details based on the selected ID
return PartialView("Details", model);
}
Note also, remove the onchange="onChange() from your <select>. I also recommend you learn to use #Html.DropDownListFor() for generating you <select> controls

How to pass dropdownlist Id as parameter to javascript function?

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 + ");"

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

Categories

Resources