I'm srugelling with this,
Working on MVC, upon change on Html.TextBoxFor value I want to change a readonly attribute of another Html.TextBoxFor.
I tried several ways-using IE it does not work.
here some code:
#Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" })
<script>
function ReadOnlyHandle() {
//document.getElementById("NoDiffNum").readOnly = true;
var startHSelect = document.getElementById("NoDiffNum");
debugger;
startHSelect.setAttribute("readonly", "true");
}
debugger;
</script>
and the row in a table I would like to change:
<td id="NoDiffNum">#Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet)</td>
the readonly attribute did not changed -
any help is most welcome!
document.getElementById("NoDiffNum") refers to the <td> element not the text box. You are setting readonly on the td.
You need to target the text box, not the td, so move the id to the text box.
<td>#Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet, new { id="NoDiffNum" })</td>
Without jQuery
function ReadOnlyHandle() {
var startHSelect = document.getElementById("NoDiffNum");
startHSelect.setAttribute("readonly", "readonly");
}
And with jQuery in your function
function ReadOnlyHandle() {
$("#NoDiffNum").prop("readonly", true);
}
If we use jQuery we can drop the inline onchange
#Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions" })
And we setup a handler
$(document).ready(function() {
$("#ExamOptions").on("change", function(event) {
ReadOnlyHandle();
});
});
Edit
Based on a value in TextBoxFor element value I want another TextBoxFor element to change its readonly attribute on and off. <div class="editor-field"> #Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" }) #*#Html.EditorFor(model => model.NumberOfQuestion)*# #Html.ValidationMessageFor(model => model.NumberOfQuestion) </div>
From your comments it's now less clear what you want to set readonly. But in any case you adjust the target id in the change handler.
var targetId = "NumberOfQuestion";
$("#" + targetId).prop("readonly", true);
Related
I have a group of dynamically generated input fields. I want to loop through all of them and check if the user has indeed written something on them. If all fields have been filled, activate the button, otherwise, desactivate it. Code is really long, so here is the most important part :
//Here is the loop that creates the number of inputs to create based on what the user enters:
(CourseObject.course_array).forEach((evaluation,value) => {
const percentage_value = CourseObject.each_evaluation_value[value];
//Some lists
const li_inputs = document.createElement('li');
li_inputs.id = ((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
li_inputs.className = "list-group-item";
(document.getElementById(`${CourseName}-input-ul`).appendChild(li_inputs));
//Here starts the important stuff, creation of the inputs and attributes
const text_input = document.createElement('input');
text_input.type = 'text';
text_input.placeholder = `Nota de ${evaluation} (${percentage_value}%)`;
text_input.id = ((`${evaluation}-of-${CourseName}-input-text`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
text_input.className = 'form-control grade-input';
(document.getElementById(((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase())).appendChild(text_input);
}
);
//Creating the button
const SendAndShow = document.createElement('button');
SendAndShow.textContent = 'Calcular';
SendAndShow.id = 'send-and-show-button';
SendAndShow.disabled = true; //Desactivated from the beggining
SendAndShow.className = 'btn btn-dark';
document.getElementById('second-column').appendChild(SendAndShow);
//Here I want to loop through the inputs. If they are all filled, SendAndShow.disabled = false
//A random event set to be activated once the button is clicked
document.getElementById('send-and-show-button').onclick = function() {
.
. //Something to do
.
}
I have tried querySelectorAll and getting the element by class but I can't seem to be able to hack it, any suggestions?
Note : I would like a pure JS answer, no JQuery.
You can use the onchange method in every input element, then check the values of inputs with FormData
const form = document.querySelector('#form')
function getFormData() {
formData = new FormData(form)
console.log(formData.entries())
}
text_input.onchange = function(){
getFormData()
}
<form id='form'></form>
for dynamic element add listener to the parent or body then check your input elements
createInput.addEventListener('click', function() {
let input = document.createElement('input')
myform.prepend(input)
submit.setAttribute('disabled', '')
})
// the parent
myform.addEventListener('input', function(el) {
if (el.target.tagName != 'INPUT') return;
// chack all input
let allFilled = true
document.querySelectorAll('#myform input').forEach(function(input) {
if (!input.value)
allFilled = false;
})
// set the button state
if (allFilled)
submit.removeAttribute('disabled')
else
submit.setAttribute('disabled', '')
})
input{display:block;margin:10px;}
<button id="createInput">Create input</button><br><br>
<form id="myform">
<button id="submit" disabled>Submit</button>
</form>
I have one dropdown and one actionlink.
where this actionlink will be clicked automatically when the dropdown changes. How to do that?. below is my code, thanks.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control" })
#Html.ActionLink(
"Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = Model.PaymentCode }, new { #class = "ddlSubmit"})
Controller
public ActionResult GetInsuranceCompany( ParamBlacklistPembayaranViewModel model,string id)
{
LoadThirdPartyDDL(string.Empty, string.Empty, id);
return View("Create", model);
}
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control",#id="ddl" })
#Html.ActionLink("Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = "PaymentCodeVal" }, new { #id="anchorclick",#class = "ddlSubmit"})
You should call click event on drop down change like this:
<script>
document.getElementById('ddl').onchange = function () {
var path = document.getElementById('anchorclick').href;
path = path.replace("PaymentCodeVal", document.getElementById('ddl').value);
document.getElementById("anchorclick").href=path;
document.getElementById('anchorclick').click();
};
</script>
#NOTE : You want get updated PaymentCode. you have to inject url to pass PaymentCode on change event.
Assign onchange event in new {} section where you can raise the event of the particular action link by using their id.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control", #id = "MyId", onchange = "MyFunction()" })
<script type="text/javascript">
function MyFunction() {
//alert('Changed');
document.getElementsByClassName("ddlSubmit").click();
$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
References:
Handling onchange event in HTML.DropDownList Razor MVC
Below is my grid code, how do I get the Primary Key Value when the cell is clicked in jquery?
I have tried searching online and can't find a working example. Is there another way to get the value without using jquery or javascript?
<div id="CampaignGrid">
#(Html.EJ().Grid.Test.Test>("Grid")
...
})
.Columns(col =>
{
col.Field("iCampaign").HeaderText("Campaign").IsPrimaryKey(true).TextAlign(TextAlign.Left).Width(50).AllowEditing(false).Add();
col.Field("vCampaignName").HeaderText("Campaign Name").IsPrimaryKey(false).TextAlign(TextAlign.Left).Width(260).AllowEditing(false).Add();
})
when you are setting fields like col.Field("iCampaign"), you determine a tag with attribute name="iCampaign",which will be used in model binding.
so you can use a jquery selector like this :
$('[name = "iCampaign"]')
you can also solve your problem this way :
#(Html.EJ().Grid<EmployeeView>("MasterGrid")
.Datasource((IEnumerable<object>)ViewBag.datasource1)
.SelectedRowIndex(0)
.Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(125).Add();
col.Field("FirstName").HeaderText("First Name").Width(100).Add();
col.Field("LastName").HeaderText("Last Name").Width(100).Add();
col.Field("Title").HeaderText("Title").Width(150).Add();
col.Field("BirthDate").HeaderText("Birth Date").TextAlign(TextAlign.Right).Width(100).Format("{0:MM/dd/yyyy}").Add();
col.Field("Country").Width(100).HeaderText("Country").Add();
})
.ClientSideEvents(eve => { eve.RowSelected("rowSelected"); })
)
<script type="text/javascript">
$(function () {
window.rowSelected = function (args) {
var employeeID = args.data.EmployeeID;
var detaildata = ej.DataManager(window.gridData).executeLocal(ej.Query().where("EmployeeID", ej.FilterOperators.equal, employeeID, false).take(10));
var gridObj = $("#DetailGrid").ejGrid("instance");
gridObj.model.dataSource = ej.DataManager(detaildata.slice(0, 5));
$("#DetailGrid").ejGrid("refreshContent");
}
});
</script>
You can try this
#(Html.EJ().Grid<EmployeeView>("MasterGrid")
.Datasource((IEnumerable<object>)ViewBag.datasource1)
.SelectedRowIndex(0)
.Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(125).Add();
col.Field("FirstName").HeaderText("First Name").Width(100).Add();
col.Field("LastName").HeaderText("Last Name").Width(100).Add();
col.Field("Title").HeaderText("Title").Width(150).Add();
col.Field("BirthDate").HeaderText("Birth Date").TextAlign(TextAlign.Right).Width(100).Format("{0:MM/dd/yyyy}").Add();
col.Field("Country").Width(100).HeaderText("Country").Add();
})
.ClientSideEvents(eve => { eve.CellEdit("cellEdit"); })
)
<script type="text/javascript">
function cellEdit(args)
{
var pkName = args.primaryKey[0];
var pkValue = args.rowData[pkName];
}
</script>
So, I want to change my checkbox, that has checked and unchecked state to radio buttons that say, Yes (checked) or No (unchecked).
Here's what I did for the checkbox:
In my view:
#Html.CheckBoxUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
js:
$('input:checkbox[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
if (!Perpendicular) {
$("#PerpendicularCheckbox").prop("checked", false);
}
else {
$("#PerpendicularCheckbox").prop("checked", true);
}
I was wondering what would I need to change it to radio buttons, yes and no options, using html extension in asp.net mvc?
EDIT:
My loosy attempt at radio buttons:
#Html.RadioButtonForUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
$('input:radio[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
RadioButtonForUi :
public static MvcHtmlString RadioButtonForUi<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string name,
bool IsEnable,
bool IsChecked,
object onchange = null,
string className = "",
bool isRequreid = true
) {etc.....}
Here is a tested sample:
<div class="form-group">
#Html.LabelFor(model => model.SaleOfPropertyPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, true, new { id = "SaleOfPropertyPurchase-true" }) Yes
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, false, new { id = "SaleOfPropertyPurchase-false" }) No
#Html.ValidationMessageFor(model => model.SaleOfPropertyPurchase, "", new { #class = "text-danger" })
</div>
</div>
</div>
Here is some sample jquery that reacts to the radio button click, and also sets up initial display on the form:
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#CurrentPropertyOwner-true').on('change', function () {
$('#CurrentProperty').show();
});
});
$(function () {
$('#CurrentPropertyOwner-false').on('change', function () {
$('#CurrentProperty').hide();
});
});
$(document).ready(function () {
var ischecked = $('#CurrentPropertyOwner-true').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').show();
}
var ischecked = $('#CurrentPropertyOwner-false').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').hide();
}
});
</script>
You need to render two radio buttons for the property, one with the value of "True" and the other with the value of "False" so the selected value can be bound to a boolean value
You custom html helper would need to be
namespace YourAssembly.Html
{
public static class MyHelpers
{
public static MvcHtmlString BooleanButtonsFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
StringBuilder html = new StringBuilder();
// Yes button
string id = string.Format("{0}-yes", name);
html.Append(helper.RadioButtonFor(expression, "True", new { id = id }));
html.Append(helper.Label(id, "Yes"));
// No button
id = string.Format("{0}-no", name);
html.Append(helper.RadioButtonFor(expression, "False", new { id = id }));
html.Append(helper.Label(id, "No"));
// enclode in a div for easier styling with css
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobuttongroup");
div.InnerHtml = html.ToString();
return MvcHtmlString.Create(div.ToString());
}
}
}
then add a reference to the <namespaces> section of web.config
<add namespace="YourAssembly.Html "/>
and use it in the view
#Html.BooleanButtonsFor(m => m.YourBoolProperty)
I have one Table that is named CustomPickedTable, this Table have rows with attribute such as <td Data-question-id="5">Example</td> and some of the rows do not have any attribute at all. just <td>example</td>.
I want to do be able to sort em into different hiddenfields, these are my hiddenfields:
#Html.HiddenFor(model => model.SelectedCustomQuestions, new { #id = "SelectedQuestionsWithAttr" })
#Html.HiddenFor(model => model.SelectedQuestions, new { #id = "SelectedQuestionsWithNoAttr" })
the code that I have right now is that all rows with attribute "data-question-id" gets filled to SelectedQuestionsWithAttr that is my hiddenfield for rows with attributes.
But I want that my Jquery code also fills those rows with no attributes gets filled to my SelectedQuestiosnWithNoAttr hiddenfield.
This is the code for Just filling SelectedQuestionsWithAttr hiddenfield:
var selectedQuestionsWithAttr = $("#SelectedQuestionsWithAttr");
var currentIds = new Array();
$("#CustomPickedTable").find("td").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
selectedQuestionsWithAttr.val(currentIds.join(","));
$("form").submit();
}
Is there any solutions that can I add to my jquery code for this?
Thanks in Advance
You would need to add something onto the <td> tags to be able to identify them:
<td id="noAttr#(Model.SelectedQuestions.IndexOf(variable))">
Then the jQuery would be:
var $qWithAttr = $("#SelectedQuestionsWithAttr");
var $qWithoutAttr = $("#SelectedQuestionsWithNoAttr");
var currentIds = new Array();
var missingIds = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
currentIds.push($(this).attr("data-question-id"));
});
$("#CustomPickedTable td:not([data-question-id])").each(function () {
missingIds.push($(this).attr("id"));
});
$qWithAttr.val(currentIds.join(","));
$qWithoutAttr.val(missingIds.join(","));
$("form").submit();