mvc 4 How to call javascript function after #Html.RadioButtonFor clicked - javascript

View Has :
<div Monthly #Html.RadioButtonFor(m => m.DDPaymentOption, "Monthly", true)
Yearly #Html.RadioButtonFor(m => m.DDPaymentOption, "Yearly", true)
</div>
tried
$(":radio").click(function () {
var Selectedvalue = $(this).val();
var isDiv = document.getElementById('instalmentScheduleDiv');
if (Selectedvalue == "Yearly")
{
isDiv.className = "HideDiv";
}
});
Does not hit the function

Use this code
$('#DDPaymentOption').click(function(){
if($(this).val()=='Yearly')
{
$('#instalmentScheduleDiv').addClass('HideDiv');
}
});
And if you are using HideDiv Class to hide the div you can jquery methods to show or hide your div element like
$('#instalmentScheduleDiv').hide(); // to hide the element
and/or
$('#instalmentScheduleDiv').show(); // to show the element

$("input[type=radio]").change(function () {
var Selectedvalue = $(this).val();
var isDiv = $("#instalmentScheduleDiv");
if (Selectedvalue == "Yearly")
{
isDiv.hide();
} else {
isDiv.show();
}
});

All credit goes to: codingbiz
This is how you can do this.
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
#Html.Hidden("PostID", Model.addcomment.PostID)
//OR
#Html.HiddenFor(model => model.addcomment.PostID)
How do I update a model value in JavaScript in a Razor view?

Related

Javascript - need to get a value from an HTML table ROW/CELL and then check true or false in script

I have a simple table. When a user clicks on a row, a jscript gets triggered. How can I get a value from row/cell to use in jscript to check true or false please? There is also a seperate click-row script but ignore that for now.
<tbody>
#if (Model != null)
{
foreach (CELIntranet.Models.tblReportsList item in Model)
{
<tr class="clickable-row" id="myid" data-mydata1=UserPermission href="#Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
<td>#Html.Raw(item.ReportNumber)</td>
<td>#Html.Raw(item.ReportName)</td>
<td>#Html.Raw(item.ReportGroup)</td>
<td>#Html.Raw(item.ReportStatus)</td>
#if (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))
{
<td style="color:dodgerblue">Granted</td>
}
else
{
<td style="color:orangered">Restricted</td>
}
</tr>
}
}
</tbody>
<script type="text/javascript">
$(function () {
var ClickedTableRowCellValue = ("Need some code to get UserPermission value from the clicked row");
$('table > tbody > tr').click(function () {
if (ClickedTableRowCellValue == True) {
alert("Granted");
Popup();
}
alert("Restricted");
});
});
</script>
// Click row ignore this code for now!
#section Scripts {
<script type="text/javascript">
var clicker = new TableCliker();
$(document).ready(function () {
clicker.Initialise();
//alert("Test");
//Popup();
});
</script>
Try to change your html like this:
<tr class="clickable-row" id="myid" onclick="test(this)" UserPermission = "#(User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))" data-mydata1=UserPermission href="#Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
So that you can add UserPermission attribute to <tr></tr>.Here is the js:
function test(t){
var ClickedTableRowCellValue = $(t).attr("UserPermission").
if (ClickedTableRowCellValue == True) {
alert("Granted");
Popup();
}
alert("Restricted");
}
Since the click() event returns the exact element that was clicked you can simply use this (the element that is clicked). And get the attribute UserPermission.
$('tr').click(function () {
var authorized = $(this).attr("UserPermission");
if (authorized) { // you don't need to state == true since it will compare to true by default
alert("Granted");
Popup();
}
alert("Restricted");
});

RadioButtonFor doesn't call onchange after load the page

not sure the title makes sense, but I have the code bellow to hide/show some fields when we select a yes/no radiobutton
<div class="container" style="width:100%;margin-top:2%">
#if (Model != null)
{
using (Html.BeginForm("NextButton_Click", "Questionnaire", FormMethod.Post))
{
<table class="table table-hover">
<tbody>
#for (int i = 0; i < Model.QuestionsPaging.Count(); i++)
{
...
<tr>
<td>
<p>
#Html.RadioButtonFor(n => n.QuestionsAnswers[index].HasAnswer, false, new { #radioIndex = i, #onchange = "CallChangefunc(this)" }) #Html.Label("No")
#Html.RadioButtonFor(n => n.QuestionsAnswers[index].HasAnswer, true, new { #radioIndex = i, #onchange = "CallChangefunc(this)" }) #Html.Label("Yes")
</p>
<div id="div_questions_#i" style="display:none">
...
</div>
</td>
</tr>
}
</tbody>
</table>
}
}
<script type="text/javascript">
function CallChangefunc(myRadioButton) {
var divName = "div_questions_" + myRadioButton.getAttribute("radioIndex");
var divElement = document.getElementById(divName);
if ($(myRadioButton).val().toLowerCase() === "true") {
if (divElement.style.display != 'inline') {
divElement.style.display = 'inline';
}
} else {
if (divElement.style.display != 'none') {
divElement.style.display = 'none'
}
}
}
</script>
The code works fine, I click the radiobutton and it hides/shows the divs as expected. The problem I'm having is that when I load the form it selects the RadioButton as expected but the event 'onchange' doesn't get triggered, so I have all fields hidden even with some radiobuttons set to yes.
I don't have too much experience in web, not sure how can I fix it, I've tried some stuffs but didn't work, any help is welcome.
Thank you.
Solution: Thanks #jom
I added " $(':radio[id^="QuestionsAnswers"]').trigger('change');" and checked if the radiobutton is checked, because ".trigger('change')" trigger the event for every radiobutton, now I have:
<script type="text/javascript">
$(document).ready(function () {
$(':radio[id^="QuestionsAnswers"]').trigger('change');
});
function CallChangefunc(myRadioButton) {
var divName = "div_questions_" + myRadioButton.getAttribute("radioIndex");
var divElement = document.getElementById(divName);
if ($(myRadioButton).val().toLowerCase() === "true" && myRadioButton.checked) {
if (divElement.style.display != 'inline') {
divElement.style.display = 'inline';
}
} else if ($(myRadioButton).val().toLowerCase() === "false" && myRadioButton.checked) {
if (divElement.style.display != 'none') {
divElement.style.display = 'none'
}
}
}
</script>
Do this on either $(document).ready or before the closing </body> tag.
$(':radio[id^="QuestionsAnswers"]').trigger('change');
// Or attach the handlers by script instead of going through Razor engine
$(':radio[id^="QuestionsAnswers"]').change(function () {
CallChangefunc(this);
});
Add $(document).ready before function CallChangefunc(myRadioButton)

Pass input text value to javascript not working

Good day. I have read and done almost all of the solution in the questions but cant seem to solve my problem. As written in my question, in mvc, i am passing a value from controller to view a string and then get by javascript to run a modal if ever a certain condition is met. please help. thanks.
here is the code in my controller:
public ActionResult Series()
{
List<sample> series = db.samples.Where(x => x.status == "False").ToList();
if ( series.Count == 0)
{
ViewBag.Info = "None";
}
else {
ViewBag.Series = series;
ViewBag.Info = "Have";
}
return View();
}
My View:
<input type="text" value="#ViewBag.Info" id="info" name="info" />
My Javascript:
#section Scripts{
<script>
$(window).on('load', function () {
var modelll = document.getElementById("#(ViewBag.Info)").value;
var s_end = document.getElementById("myNumber2").value;
var s_current = document.getElementById("myNumber3").value;
var s_status1 = document.getElementById("status").value;
var s_id1 = parseInt(document.getElementById("myNumber").value);
var s_end2 = parseInt(s_end, 10);
var s_current2 = parseInt(s_current, 10);
var x = parseInt(s_current, 10) + 1;
document.getElementById("item1").value = s_id1;
document.getElementById("item2").value = s_end;
document.getElementById("item3").value = x;
document.getElementById("status2").value = s_status1;
if (modelll === 'Have')
{
if ((s_current2 > s_end2) && (s_current2 != s_end2)) {
$('#myModal').modal({ backdrop: 'static', keyboard: false });
$('#myModal').modal('show');
}
}
else
{
$('#myModal').modal({ backdrop: 'static', keyboard:false });
$('#myModal').modal('show');
}
});
</script>
}
getElementById need an ID but you are passing #ViewBag.Info. change it to :
var modelll = document.getElementById("info").value;
also you are making many extra variables which are not really needed. for example to get what you have in s_current2, you can use
var s_current = parseInt(document.getElementById("myNumber3").value, 10);
no need to create another variable to convert it to integer.
To get the value from textbox
var modelll = document.getElementById("info");
To set the value to textbox
document.getElementById("info").value = var modelll;
you are using #ViewBag.Info instead of element id.
Following line is causing the problem in your code :
var modelll = document.getElementById("#(ViewBag.Info)").value;
// document.getElementById needs Id but you are passing #(ViewBag.Info) which is wrong
var modelll = document.getElementById("info").value; //info id of your textbox
// now check
if (modelll === 'Have')
{ }
else
{ }

Autocomplete on wrong form field

I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>

remove value from the list

I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.

Categories

Resources