How to get text from a textbox using javascript - javascript

i have developed a web application using mvc4.
in this case i need to get a text box value(actually the text entered in the text box) using javascript.
here is the code i am using
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
in that case alert gives the value as "undefined" and if do the following modification alert gives nothing.
var imgNm = document.getElementById("Name").value;
for
var imgNm = $("#Name").value;
how to get the text entered in the text box?

You should use val() function for that:
var imgNm = $("#Name").val();

If you're using native javascript you should use this:
var userImgNameElement = document.getElementById("userImgNameId");
var userImgNameValue = userImgNameElement.getAttribute("value");
With "onChanged" event:
addEvent(document.getElementById('userImgNameId'), 'change', function(event) {
var userImgNameValue = event.target.getAttribute("value");
});

In an input element, the value of can be found in a value property of that element. It can therefore be retrieved via document.getElementById('idOfElement').value.
In an textarea element has it's value between the starting and the closing tag. Therefore, the value property is empty. In raw javascript, you would be able to retrieve the contents with document.getElementById('idOfElement').innerText.
If you are however using jQuery, Ufuk's solution with .val() is much easier to use.

Related

Append search results to respective parent div?

I'm implementing autocomplete using webSocket. When I type in the input field which has the classname item-search-results, a bunch of result will show up search results screenshot. My problem is the result will is only attach to the very first item-search-results input field.
But I need the results show up under the right item-search-results input field.
For example, I type on the 4th item-search-results input field, but the results are attach to the first one results are attach to the first row screenshot
Here is my webSocket js, I use jQuery:
$(function () {
let webSocket = new WebSocket("ws://localhost:8000/autocomplete");
webSocket.onopen = (msgEvent) => {
console.log('connected to WebSocket!');
};
webSocket.onmessage = (msgEvent) => {
/* results shows {"results":{"results":[{..}]}}.
results.results shows {results:[{..}]}
results.results.results shows [{...}], which is an array */
let results = JSON.parse(msgEvent.data),
resultsArr = results.results.results;
console.log(resultsArr);
$.each(resultsArr, (index, value) => {
$('<div>' + value['name'] + '</div>').attr('id', 'item-search-results-' + index).appendTo($('.item-search-results'));
});
};
webSocket.onclose = (msgEvent) => {
console.log('disconnected');
};
webSocket.onerror = (msgEvent) => {
console.log('there\'s an error');
};
/**
* Request to display data
*/
$('.add-items-table').on('input', '.item-input', (e) => {
let value = e.target.value;
webSocket.send(value);
console.log(value);
})
})
Websockets are irrelevant here, and I don't understand why you are doing an append inside loop. When trying to do something like this, you need to use the $(this) selector which will be the element you actually click.
At the top of your script create a global variable or namespace.
var Item = {};
/* In this chunk of code, create an object which you can use as a reference */
$('.add-items-table').on('input', '.item-input', (e) => {
/* this will be the correct .item-search-results div */
var Item.list = $(this).siblings('.item-search-results');
let value = e.target.value;
webSocket.send(value);
console.log(value);
})
Finally, append to the correct <div>.
.appendTo(Item.list);
Not sure about Websocket But here is how you will approach.Get last Row of table and append data after that particular row.
var placeHolder=` <tr>
<td style="width: 16.66%">
<input type="text" name="quanty" value="">
</td>
<td class="item-search-container">
<input class="item-input" id="item-input-0" type="search" name="item" value="">
<div class="item-search-results"></div>
</td>
<td>
<input type="text" name="quanty" value="">
</td>
</tr>`;
function addItem(){
let totalElem=document.getElementsByClassName('tr').length;
let lastElem=document.getElementsByClassName('tr')[totalElem-1];
$.get( "https://jsonplaceholder.typicode.com/posts/1", function( data ) {
$.each(data, function(i, item) {
$(lastElem).after(placeHolder);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="item-form">
<table class="add-items-table table table-hover ">
<thead>
<tr>
<th>Quanty</th>
<th>Item</th>
<th>Comment</th>
<th>Remove</th>
</tr>
</thead>
<tbody class="item-row">
<tr class="tr">
<td style="width: 16.66%">
<input type="text" name="quanty" value="">
</td>
<td class="item-search-container">
<input class="item-input" id="item-input-0" type="search" name="item" value="">
<div class="item-search-results"></div>
</td>
<td>
<input type="text" name="quanty" value="">
</td>
<td>
<button class="remove-item-button btn-block btn-outline-danger" type="reset" name="remove">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
<button class="add-item" onClick="addItem()">Add Another Item</button>
</section>
The problem here is that you are appending it to $('.item-search-results') that is a class and is returned as an array. When you run .appendTo($('.item-search-results')) it will append to the first item of the array.
You should use a more specific Id for each roll and append by Id.
I think #manikant 's idea of creating a template is great, but I would introduce a variable that you can change for each new row you create and give a different Id to each .item-search-results div. But you would have to send this to the websocket and receive it back to call the right Id to append.

Make a DIV show with jQuery in nested accordion structure

I have an accordion that is loaded from a model list, so it is repeated with new IDs assigned according to the ID of the model. In this structure I have a DIV is display:none and upon clicking a radio button I want it to slide down and show. This is some of my HTML:
<tr style="height:35px">
<td style="text-align:left" >
<label id="lblOtherAvery+#Model[i].UserId" style="font-size:x-small">Other:</label>
</td>
<td>
#Html.RadioButtonFor(x=>Model[i].AverySize, "Other", new { #id = "chkOtherAvery" + #Model[i].UserId, #style = "width:30px;", #class = "radLabel radLabelOther", #disabled = "disabled"})
</td>
</tr>
<tr>
<td style="text-align:center" colspan="2" >
<div id="divAvery_#Model[i].UserId" style="display:none;vertical-align:top;text-align:center" class="divAvery">
<table style="width:100%;text-align:center">
<tr style="height:20px;">
<td style="font-size:x-small">Rows:</td>
<td>#Html.TextBoxFor(x=>Model[i].LabelRows, new {#id = "txtRows" + #Model[i].Userd, style = "width:50px;font-size:x-small;height:20px"})<span style="font-size:x-small"><i>(MAX 16)</i></span></td>
<td style="font-size:x-small">Columns:</td>
<td>#Html.TextBoxFor(x=>Model[i].LabelColumns, new {#id = "txtColumns" + #Model[i].UserId, style = "width:50px;font-size:x-small;height:20px"})<span style="font-size:x-small"><i>(MAX 3)</i></span></td>
</tr>
</table>
</div>
</td>
</tr>
Then in the JS for when the radio is clicked:
$('.radLabelOther').on('click', function () {
var divId = $(this).closest('tr').next().children().find('.divAvery');
$(divid).slideDown().show();
});
But this doesn't work. I am able to get the DIV element OK, but I cannot get it to show. What am I doing wrong?
I have even tried to get the ID of the DIV with this:
var divId = $(this).closest('tr').next().children().find('.divAvery').attr('id');
But that doesn't work either.
I can get it to work now by doing this:
var $divId = $(this).closest('tr').next().children().find('.divAvery');
$divId.slideDown();
Why does that $ make it work?

KnockoutJS submit binding not working with foreach

Hello I am unable use knockout 'submit' binding with 'foreach' binding.
I cannot figure out what is mistake here.
Please help me find my mistake.
My view model is like this:
function poReceivingModel(){
var self = this;
var initial_row = new poReceivingRowModel();
self.rows = ko.observableArray([initial_row]);
self.saveAndAdd = function(formElement){
alert('entered into function');
var row = new poReceivingRowModel();
self.rows.push(row);
};
};
function poReceivingRowModel(){
var self = this;
self.building = ko.observable();
self.isele_abc = ko.observable();
self.isele_num = ko.observable();
self.isele_floor = ko.observable();
};
And my html binded to 'viewmodel' is like this:
<tbody data-bind="foreach: rows">
<form data-bind="submit: $parent.saveAndAdd">
<tr>
<td>
<!-- input field here -->
</td>
<td>
<!-- input field here -->
</td>
<td>
<!-- input field here -->
</td>
<td>
<!-- input field here -->
</td>
<td>
<button type="submit">Save and Add</button>
</td>
</tr>
</form>
</tbody>
The problem is when I click on 'Add and Save' button 'saveAndAdd' function from 'poReceivingModel' is not called.
I do not get any alert message.
I tried calling that function with 'click' binding on 'button' element. The function get called this way ie I get alert message.
UPDATE:
In firebug I see form tag is closed just after
and button is out of 'form' tag.
I found that form tag cannot be used inside table tag. Solution is table tag can be put inside form tag .
If we do not want to do so we can change the table tag to div but this may not give you desired output.

Filter kendo dropdownlist to remove options

I want to filter security questions such that if I select questiona from the list of questions, for the next questions, I no longer see questiona in the list of security questions. This is to prevent duplicate selection of security questions.
Here's a jsfiddle with a pure jquery implementation:
http://jsfiddle.net/jbfbxvoo/
I was wondering how I can use the same approach to filter kendo dropdownlists:
E.g. I have three dropdownlists like:
<table style="float: left; width:300px;">
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q1Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion1", #class="security"})
.Name("Q1DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A1, new { #class = "formTextbox k-textbox", #id = "idAnswer1" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q2Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion2", #class="security" })
.Name("Q2DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A2, new { #class = "formTextbox k-textbox", #id = "idAnswer2" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q3Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion3", #class="security" })
.Name("Q3DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A3, new { #class = "formTextbox k-textbox", #id = "idAnswer3" })
</div>
</td>
</tr>
</table>
I tried this but doesn't work:
QuestionChanged: function () {
var sec = $('.security');
sec.change(function () {
sec.find('option').show().end().each(function () {
$('option[value="' + $(this).val() + '"]:not(:selected):not([value="0"])', sec).hide();
});
}).change();
}
For this implementation i have an idea, where first you need to have 3 dropdownlist that have one same datasource/observable but three different value to store each dropdownlist value and point to one same change event, example in mvvm
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd1, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd2, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd3, events:{change:onChange}" style="width: 400px;"/>
On the view model change event you do your logic, maybe you can write better code than mine right now but the main point is
To loop through all 3 dropdownlist <li></li> , and compare with the
three value dd1,dd2,dd3 hide if match, otherwise show it
And the code :
var dropdowns = $("input.customdropdownlist");
for(j=0;j<dropdowns.length;j++){
var list = $(dropdowns[j]).data("kendoDropDownList").ul.find("li.k-item");
for(i=0;i<list.length;i++){
if(viewModel.dd1 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd1).text){
$(list[i]).hide();
}else if(viewModel.dd2 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd2).text){
$(list[i]).hide();
}else if(viewModel.dd3 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd3).text){
$(list[i]).hide();
}else{
$(list[i]).show();
}
}
}
Working example in kendo dojo, add
updated dojo from modifying your code.
I have done something similar for kendo ComboBox. Do manipulate the below js function and it will work for kendo Drop Down also.
function QuestionChanged(event) {
$("[class^=security]").each(function () {
if (event.sender.element.attr('class') != $(this).attr('class')) {
var comboBox = $('#' + $(this).attr('id')).data('kendoComboBox');
$(comboBox.dataSource.data()).each(function () {
if (event.sender._selectedValue == this.Value) {
var data = this;
comboBox.dataSource.remove(data);
}
});
}
});
}
NOTE: Add security class to each of the drop down as security1 for first drop down, security2 for 2nd drop down and so on.
Hope it helps! Feel free to leave your feedback.

how to handle partial view elements in javascript

please refer this code and it is for a partial view of my web application developed using mvc.
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
i need to handle the textchange event of this textbox in partial view using javascript code i have mentioned above
#Html.TextBoxFor(model => model.Name)
please somebody tell me how to handle the text change event of the above code line of textbox..
$document.on('blur', 'TextBox', function(){
//Do something
});
This format should work for any fields on a partial view. from here http://api.jquery.com/on/

Categories

Resources