How to get the #htmlDropDownList selected value? - javascript

I have a #htmlDropDownList as
#Html.DropDownList("MyList", new SelectList(Model.List, "Id", "Movie"))
in a mvc3 view.
How can I capture the selected value of this drop down list using javascript and use it to change the contents of the view according to the selected item?

To get the value is simple:
$('#MyList').val()
For the second part of the question I need more info.
UPDATE
How would we use the value?
//get the url for the movie description , define id as 0, so it is easier to replace lateron.
var moviedescriptionUrl = '#Url.Action("details", "movies", new { id = 0})';
//get the movieid
var movieID = $('#MyList').val();
//update a div
$('#movie-description').load(moviedescriptionUrl.replace('0', movieID));
Assuming I have an "details" action that return a partial view.

Related

Build hyperlink using value in array in javascript

I'd like to display hyperlinks in my page template based on values in an array.
If the page contains a certain value, I'd like to insert the corresponding hyperlink.
From another question, I've managed to cobble together a script that displays a link when a value is found in a string:
<style>
#viewSchoolLink
{display: none;}
</style>
<div id="schoolName">University of Houston</div>
<div id="viewSchoolLink">View on Some Link</div>
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("University of Houston") >= 0) {
// if so set display to block.
document.getElementById("viewSchoolLink").style.display = "block";
}
</script>
The thing is, I have like 80-90 schools in my list. I suppose I could create 80-90 separate divs with their own unique links, but I imagine there is a much more efficient way to do it. I have an array I've set up as follows:
const schoolLink = {
"University of Houston": "https://www.somelink.com/widget=4379",
"Vanderbilt University" : "https://www.somelink.com/widget=2537",
"University of Dundee": "https://www.somelink.com/widget=2845",
}
Is there a way I can loop through the array to find a match in the key and then insert the value from the array as a hyperlink?
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("key in array") >= 0) {
// if so display div and use value from the array as hyperlink
}
</script>
Or, since the only part of the link URL that is unique is the widget number, could I set up my array like this:
const schoolLink = {
"University of Houston": 4379,
"Vanderbilt University" : 2537,
"University of Dundee": 2845,
}
and then just build the URL based on the value in the array:
var part = value in array
var link = ''View on Some Link ';
to insert any of the HTML using Javascript we assign in the following manner:
var div = document.getElementById("schoolName")
div.innerHTML = "<a href='https://www.somelink.com/widget=value in array'/>"
if you want to enter the dynamic data in the place of "value in array", then:
div.innerHTML = `<a href="https://www.somelink.com/widget=${variable}"/>`

Angular js, on select element i want to POST data to save it in the database then i want to update it with PUT without page reload

I have a table which had a select field in it which I'd like to save into database if it dosnt exist yet through POST data. If it does exist then I'd like to update the already existing row in the database.
This can be found in the tbody in which i have my tablerow with an ng-repeat to display all data from a json.
<td>
<select id="statusSelect{{anime.id}}" ng-model="statusId" ng-options="animeStatus.id as animeStatus.status for animeStatus in animeStatuses"
ng-change='addUserAnime( "<?php echo Yii::app()->user->id; ?>", anime.id, statusId )'>
</select>
</td>
Next this is my code for what im trying to do in the angular controller:
$scope.addUserAnime = function( userId, animeId, statusId, userAnime )
{
if ( userId == '' ) {
//alert user that he/she needs to log in first
} else {
//loop through my json where i saved from which user which anime is saved with which status
for (var i = 0; i < $scope.usersAnime.length; i++) {
//if there is an already existing entry then i want to update it if not then i want to introduce it into DB with POST
if ($scope.usersAnime[i].anime_id == animeId && $scope.usersAnime[i].user_id == userId) {
$scope.userAnime = $.extend({}, $scope.usersAnime[i]);
$scope.userAnime.status_id = statusId;
$scope.userAnime.date_modified = today;
saveUserAnime();
return;
}
}
$scope.userAnime = {
id: 0,
user_id: userId,
anime_id: animeId,
status_id: statusId,
rating: '',
date_modified: today
};
saveUserAnime();
}
};
Problem is that if i POST a new entry it gets saved in the database, but if i dont reload the page and i change the select again giving it a new option it gets POSTed again instead of using PUT for update.In the end i end up with two entries instead of one. I want to introduce it to database on first select and i want to update it if its changed after. Is that possible. I tryed doing it with $dirty using the table as form but thats a nono.
In the saveUserAnime() function its correctly deffined to use POST if its new entry and use PUT if its an existing one. I have another form for which it works. The problem must be in this current function.
Just put that code where you get the object with the animeStatus and put that in a function and call it directly after that. Now you can call that function when your POST is done, so the new data will be loaded.
Otherwise you could also check through SQL, if that value exists in your table, so you don't need your check in angularjs, that would be easier than this one.

How can I get checkbox attribute with using javascript?

I' m using MVC and set an itemId attribute to checkboxes.
#Html.CheckBox("check", false, new { itemId = item.ID })
Now I want to get this attribute with using javascipt but I could not.
I got the checkboxes list with this code:
var checkboxes = document.getElementsByName('check');
Are there any solution for it?
this should help:
var itemId = document.getElementsByName('check')[0].getAttribute('itemId');

Trying to get a list of checked items on change_state in jstree

Using jsTree (pre1.0_fix_1), I would like to obtain a list of id's for all the checked items (or better, a JSON object with id AND text of each checked item). I will then make an ajax call with this. Additionally, this should happen any time there is a state change of something getting checked or unchecked.
This is what I currently have:
$(function(){
n = $('#colors').jstree({
"plugins": ["themes", "html_data", "checkbox"]
}).bind("change_state.jstree", function(e, data){
console.log($('#colors').jstree('get_selected').attr('id'));
});
});
This is just returning 'colors', from the container'sid: <div id="colors">. I fished around the data object, but didn't find it in there (perhaps I missed it?)
In order to get the checked nodes' JSON you should be using get_checked and not get_selected. Try this:
var checked = $("#colors").jstree("get_checked",null,true);
var checked_json = [];
$(checked).each(function (i,node) {
var id = $(node).attr("id");
var text = $(node).attr("text");
var node_json = {
"id" : id,
"text" : text
};
checked_json.push(node_json);
});
After that checked_json will contain an array of of id+text objects which you could send to the server.

Javascript - filling textboxes with checkbox value

In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")

Categories

Resources