RadioButtonFor doesn't call onchange after load the page - javascript

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)

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

Javascript seems not to be working on mobile

I have a text toggle option on my (WordPress) website:
If you click on the red "info" link on the right the text under it opens. The problem is that it doesn't seem to work on mobile (iPhone 4). See the screenshot attached. It seems to me the javascript is not loading at all or just not working?
html link:
<div id="<?php the_ID(); ?>" class="projectTitel">
<?php the_title( sprintf( '<h2 class="entry-title"><button rel="bookmark" class="show">', esc_url( get_permalink() ) ), '<div class="info">Info ↓</div><div class="close_info">X</div></button></h2>' ); ?>
</div>
javascript code:
<script type="text/javascript">
var divs = document.getElementsByClassName("projectTitel");
[...divs].forEach(someDiv => someDiv.addEventListener("click", handler));
// by default, all Inhoud divs are hidden
hideElements("Inhoud");
hideElements("close_info");
jQuery('.info').show();
function handler(event) {
// get the clicked project's index :
var projectIndex = getClickedProjectIndex(event);
// toggle the right Inhoud div :
toggleDiv(document.getElementsByClassName("Inhoud")[projectIndex]);
toggleDiv(document.getElementsByClassName("close_info")[projectIndex]);
toggleDiv(document.getElementsByClassName("info")[projectIndex]);
}
// hide all elements that have the provided class name
function hideElements(className) {
var elements = document.getElementsByClassName(className);
[...elements].forEach(element => element.style.display = "none");
}
function getClickedProjectIndex(event) {
var elements = document.getElementsByClassName("projectTitel");
var projectIndex = 0;
[...elements].forEach((element, index) => {
if (element.id == event.currentTarget.id) {
projectIndex = index;
}
});
return projectIndex;
}
function toggleDiv(element) {
if (element.style.display === 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
</script>
Replace "[...divs]" on "Array.from(divs)"
And do it for all other instances of [...{a}].

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

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?

Load parts of page on demand without jquery

I am completely new to web design and I am experimenting with few things.
Lets assume that I can't use jquety and I can't upload any file to the page, instead I can use simple javascript.
What I have now is a table with few tags, and a javascript function to show based on checkboxes.
Script
<script language="javascript">
function toggleTR(trId) {
var trArray = document.getElementsByTagName("tr");
for(i = 0; i < trArray.length; i++){
if(trArray[i].id == trId){
if(trArray[i].style.display == 'none'){
trArray[i].style.display = '';
}else{
trArray[i].style.display = 'none';
}
}
}
}
</script>
Checkbox
<input type="checkbox" onClick="toggleTR('TR1');"/> TR1
And simple table
<table>
<tr id="TR1" style="display: none;">
<td>content</td>
</tr>
</table>
It works as intended, however as the page gets bigger the load time is horrible.
Is there a way for those tags to be loaded on demand when display attribute is changed? I've read about lazy load, but could not get it to work with this.
Please try to explain it as easy as it could be, as I am totally inexperienced :-)
There can't be lazy load.
Your loop will keep on running till the end. Give a break statement if the id is found., so that the rest of th loop doesn't run.
<script language="javascript">
function toggleTR(trId) {
var trArray = document.getElementsByTagName("tr");
for(i = 0; i < trArray.length; i++){
if(trArray[i].id == trId){
if(trArray[i].style.display == 'none'){
trArray[i].style.display = '';
}else{
trArray[i].style.display = 'none';
}
break;
}
}
}
</script>
OR
You can find the particular element by id and toggle as desired. This would be recommended though.
var trobj = document.getElementById(trId);
if (var != null)
{
// toggle code here
}
As ID should be unique, this should be more optimised
function toggleTR(trId) {
var tr= document.getElementById(trId);
if(tr != null){
if(tr.style.display == 'none'){
tr.style.display = '';
}else{
tr.style.display = 'none';
}
}
}
And if you don't want to hide/show unique element, then you can use classes.
<table>
<tr class="TR1" style="display: none;">
<td>content</td>
</tr>
</table>
and
function toggleTR(trClass) {
var tr= document.querySelectorAll('.'+trClass);
if(tr != null){
for(var i = 0, l = tr.length; i < l ; i++){
if(tr[i].style.display == 'none'){
tr[i].style.display = '';
}else{
tr[i].style.display = 'none';
}
}
}
}

Hiding/displaying Divs onChange

I have a variety of divs with form fields. Based on a drop-down list, i need it to display the div corresponding to that value, and hide all the other divs. (Perhaps there's a more efficient way to even do that, rather than load all the divs and just hide them, i'm not sure).
What I have right now is this:
<select id="group" name="group">
<option></option>
<option value="8">Testing This Stuff</option>
<option value="9">Testing Other Stuff</option>
</select>
<div id="8" style="display:none;">**form fields**</div>
<div id="9" style="display:none;">**different form fields**</div>
And the current, semi-working javascript:
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.selectedIndex;
document.getElementById(id).style.display = 'block';
}
}
</script>
What i'm getting is 'id' is null, so i haven't been able to work past that part yet.
Part 2 would be hiding the old div and displaying the new div (if they were to change the option selected). Any suggestions?
Solution:
<script type="text/javascript">
window.onload = function() {
var current;
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
</script>
<select id="materialsgroup" class="formInput" name="materialsgroup">
<option value=""></option>
<option value="groupid_8">Testing This Stuff</option>
<option value="groupid_9">Testing Other Stuff</option>
</select>
<div id="groupid_8">**form fields**</div>
<div id="groupid_9">**more form fields**</div>
To make the select and divs, this is what I've done:
foreach($groups as $key=>$value)
{
$valueItem = "groupid_".$value['group_id'];
$text = $value['title'];
$htmlString .= sprintf('<option value="%s">%s</option>', $valueItem, $text);
}
echo '<tr>
<td class="formLabelCell">Group</td>
<td class="formInputCell">
<select id="group" class="formInput" name="group">'.$htmlString.'</select></td></tr>';
foreach($groups as $gkey=>$gvalue)
{
echo '<div id=groupid_'.$groups[$gkey]['group_id'].' style="display:none;">';
//**Draw the form stuff here**
echo '</div>';
}
Try using
var id = eSelect.value;
For the second part, if you are using pure javascript (I mean, you're not using a javascript framework like jQuery) maybe a good solution is to load an array containing the div's ids and iterate it, hiding the div != eSelect.value
var arrDivs = new Array("1","2","3");
for (var i=0; i < arrDivs.length; i++) {
if (arrDivs[i] == eSelect.value)
document.getElementById(arrDivs[i]).style.display = 'block';
else
document.getElementById(arrDivs[i]).style.display = 'none';
}
I'm a javascript novice myself, but what about using a current variable to show which div is shown (and therefore knowing which div to hide)?
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}

Categories

Resources