I have a textfield which is NOT enclosed in a form. Using javascript I need to extract the textfield value. How can I do this ?
I am using C#-Razor in my front end.
HTML Razor Syntax : (Note: this textfield is not enclosed in a form, and I don't want it to be enclosed in a form)
<div class="form-group">
#Html.TextBoxFor(model => model.NAME, new { #class = "control-label col-md-12", placeholder = "Name" })
#Html.LabelFor(model => model.NAME, new { #class = "col-md-12 " })
#Html.ValidationMessageFor(model => model.NAME)
</div>
Javascript code
$(document).ready(function () {
$('#UseShipAddr').click(function () {
alert(document.getElementById("NAME"));
}
});
Output I get
[HTMLInputElement]
You are alerting the actual html element itself. You need to get the value like this:
document.getElementById("NAME").value
Related
In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});
Everything works perfectly with create/edit pages, where CKEditor encodes input and server side returns decoded for CKEditor to display.
All that goes out of the window when validation error occurs making page reload after it hit the server.
Even though I am decoding on return to the view, CKEditor won't properly render html tags.
If I do Html.Raw for the same field, I can see its showing html properly, so its no the issue with decoding. For the life of me I can't figure out why this case is any different from editing ( loading existing html into CKEditor from dB) which works perfectly. But on page reload it all goes out of whack.
Things I've tried, decoding, encoding, neither. Adding delay to CKEditor initialization.
Server side return code.
if (!ModelState.IsValid)
{
q..Text = System.Net.WebUtility.HtmlDecode(q.Text);
return View(q);
}
View
<div class="form-group">
#Html.LabelFor(model => model.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Question.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Raw(Model.Text)
</div>
</div>
JavaScript for CKEditor
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('Text', { htmlEncodeOutput: true, enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.Text;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
};
</script>
Using CKEditor v4.8.0 • 13-12-2017
Image to show the issue, below CKEditor #Html.Raw(Model.Text) output, showing that html is decoded properly.
Resolved this by using #Html.Raw(Model.Text) Instead of TextAreaFor
With #Html.HiddenFor(model=>Model.Text)
To preserve data when posting to server/controller
And Javascript to update hidden field and encode html
<script type="text/javascript">
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('ckEditorRaw', { enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.ckEditorRaw;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
//Set hidden field and escape html
$("#Question_Text").val(new Option((ckEditorInstance.getData())).innerHTML)
};
</script>
I need to use jQuery to add some elements dynamically. So I looked up in the internet and I found this. It is nice and working when there is plain html elements inside single quotes. I need to use razor syntax with jQuery.
I understand that jQuery is user side and razor is server side. They cannot be combined together. I am asking here because I need to know how do i achieve this.
My not working jQuery is as follows:
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".btnPlus", function () {
var html = '<div class="form-group">'+
'#Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" })'+
'<div class="col-md-4">'+
'#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" })'+
'#Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" })'+
'</div>'+
'<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+
'</div>'
$("#trItem").append($(html))
};
});
My aim is similar to the tutorial - to add elements dynamically. Here I am adding a label and dropdown on the click of button. How do I achieve this?
You cannot add Razor elements using JQuery because, as you have stated, JQuery is a client side library and ASP.NET using Razor syntax is a server side scripting language.
If you want to add elements created using Razor syntax then add a hidden element to the page and use JQuery to add a clone of it to the DOM.
Something like this should give you an idea of what I mean:
#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control", #id = 'template-ddl' })
$("#trItem").append($('#template-ddl').clone());
You can create a partial page _MyPartial.cshtml in your Views Shared folder.
Then in your view reference add the reference to your scripts section
#section Scripts {
#Html.Partial("~/Views/Shared/_MyPartial.cshtml",Model);
}
Partial page: _MyPartial.cshtml
#model MyViewModel
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".btnPlus", function () {
var html = '<div class="form-group">'+
'#(Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" }))'+
'<div class="col-md-4">'+
'#(Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" }))'+
'#(Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" }))'+
'</div>'+
'<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+
'</div>'
$("#trItem").append($(html))
};
</script>
It is best to avoid generating jQuery/Javascript code with Razor. For many reasons your Javascript/jQuery code is better off in separate files (VS debugging/script bundling etc)
Instead inject the templated HTML into a hidden part of the page. A dummy script block works great for this as the browser will just ignore an unknown script type:
<script id="template" type="text/template">
<div class="form-group">
#Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" })
</div>
<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>
</div>
</script>
You can see what is generated with your DOM inspector to ensure the correct attributes are present.
Then simply use that HTML from the template to add new buttons:
$("#trItem").append($('#template').html());
The only issue you need to resolve is any duplicate IDs and indexing for multiple items. I usually use raw HTML in the template (not Razor) and use placeholders for the various attributes that need renaming.
e.g.
<script id="template" type="text/template">
<div class="form-group">
<label for="{id}"/>
I'm trying to save number with thousands separator inside number field
1000 >> 1,000
100000 >> 10,000
2000.02 >> 2,000.02
i want to use js and jquery for this issue,
i want thousands separators become visible when the user is typing.
<div class="form-group">
<label class="control-label col-md-2" Sum</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Sum, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.Sum, "", new { #class = "text-danger" })
</div>
</div>
Any help?
You can try autoNumeric plugin. Basic init will do what you need:
$('#Sum').autoNumeric('init');
Check section:
The basics on getting autoNumeric() up and running with the initialize
'init' method and default settings: ...
I want to get the value of an EditorFor in ASP but it returns me nothing.
Thank you for your helps
<div class="form-group" id="ParticipantNumber">
#Html.LabelFor(model => model.ParticipantNumber, new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.ParticipantNumber)
</div>
</div>
My JavaScript code
$('#ParticipantNumber').keyup(function () {
var s = $('#ParticipantNumber').val();
console.log(s)
}
Your JavaScript is looking for $('#ParticipantNumber'), which is the element with the ID ParticipantNumber. Your code defines the editor with:
#Html.EditorFor(model => model.ParticipantNumber, new {
#class = "ParticipantNumber", disabled = "disabled" })
The intention here is to assign the input with the class ParticipantNumber, which would have meant you could address it with `$('.ParticipantNumber') instead.
However, the parameter you're using is additionalViewData; the EditorFor HTML editor does not have a property to reflect HTML properties back into the renderer. Your two options are:
Write a custom template
Change the way you're referencing the input
Option 1 is possibly a bit over-the-top for your needs; with option 2, the following will solve your problem, by simply referencing the input within your <div id='ParticipantNumber'>:
#Html.EditorFor(model => model.ParticipantNumber)
$('#ParticipantNumber input').keyup(function () {
var s = $(this).val();
console.log(s)
}
I'm a bit late coming to this party but I recently had this issue with Html.EditorFor.
What fixed it for me was to simply switch to TextBoxFor. So instead of:
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Change it to:
#Html.TextBoxFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
In the javascript, you are querying for the "id" attribute, but #Html.EditorFor does not emit any id by default. You can modify your code like this
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Then your javascript will work.