Mapping not working in knockout with the button click - javascript

Mapping not working in knockout with the button click,
I have used mapping in knockout, while changing input text value when clicking button not changed properly.
Need to change value for name input text after click load user data button
Here my code,
<div class='sample'>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>
<p>Save: <input type="button" value="Save User Data" data-bind="click: saveUserData" /></p>
</div>
<script>
$(document).ready(function () {
var viewModel = {};
viewModel.firstName = 'Knockout JS';
viewModel.loadUserData = function () {
$.getJSON("/data.json", function (data) {
// update the data in existing ViewModel.
viewModel.firstName = data.name;
ko.mapping.fromJS(data, viewModel);
});
};
viewModel.saveUserData = function () {
// Convert the viewModel into JSON.
var data_to_send = { userData: ko.toJSON(viewModel) };
// Send that JOSN data to server.
$.post("WebService.asmx/updateData", data_to_send, function (data) {
alert("Your data has been posted to the server!");
});
};
ko.applyBindings(viewModel);
});
</script>
Did i anything wrong?

In order to make it update the UI, you need to make the firstName observable.
Then when you want to modify an observable value, you need to treat that as a function and pass the new value as an argument like this firstName('newValue')
See the link here to get more information and a sample below:
var masterVM = (function () {
var self = this;
self.firstName = ko.observable("Knockout JS");
self.loadUserData = function() {
var currentName = self.firstName();
self.firstName(currentName + "Updated");
}
})();
ko.applyBindings(masterVM);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>

Related

Dynamically pass in values to the data object

Currently, I get the value of an id and pass it in my data object to be sent to the server.
const field_value = $('#id_field').val();
const scores_value = $('#id_scores').val();
$.ajax({
data: {'Fields':field_value, 'Scores': scores_value},
});
I want to achieve this dynamically in case I add more forms so it can automatically update without me having to change any code.
I tried using the jquery each method to access the class.
$(".class").each(function() {
const get_updated_value = $(this).val();
});
This dynamically gets the values, but I am having trouble passing the returned values to the data object.
If each element with '.class' has still an own id you could take these id's as the keys of the data object:
var updated_values = {};
$(".class").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
$.ajax({
data: updated_values,
});
Working example:
function update() {
var updated_values = {};
$(".input").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
console.log(updated_values);
}
input {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" placeholder="My task" id="field" class="input">
<input type="text" placeholder="My date" id="scores" class="input">
<input type="text" placeholder="My time" id="something_new" class="input">
<input type="button" value="Update" onclick=update() id="save">
</div>

Sending only the updated object from ko.observableArray

How can I send only the updated model from an observable Array instead of sending the entire array?
var student = function (){
this.studentId=0;
this.firstName=ko.obserable();
this.lastName=ko.obserable();
}
var course= function (){
this.courseId=0;
this.students=ko.obserableArray([]);
this.Name=ko.obserable();
}
Now I want to get only that particular student from course whose info is updated. Assuming that when we add a new class we can dynamically add new students to it on the go. Supposing that you have to validate the previous student before adding a new one. When I get that particular student I want to send that student info back to the server.
Thanks.
If I understood your task right, you could use "arrayChange" event type to get exact changed (added/removed) items:
sourceArray = ko.observableArray();
sourceArray.subscribe(function (changes) {
changes.forEach(function(arrayChange) {
if(arrayChange.status === 'added') {
// some code on add
} else if(arrayChange.status === 'deleted') {
// some code on delete
}
});
}, null, "arrayChange");
If you want to get list of students which have been modified, you can provide a flag to identify if an object has been modified in student object. Use .subscribe to modify that flag whenever a value is updated. Then use ko.computed or ko.pureComputed to get that list.
Also it supposes to be observable.
var student = function (id, firstName, lastName) {
var self = this;
self.hasChanged = ko.observable(false);
var modified = function(){
self.hasChanged(true);
};
self.studentId = ko.observable(id);
self.firstName = ko.observable(firstName);
self.firstName.subscribe(modified);
self.lastName = ko.observable(lastName);
self.lastName.subscribe(modified);
}
var course= function (){
var self = this;
self.courseId = 0;
self.students = ko.observableArray([new student(1, "Cristiano", "Ronaldo"), new student(2, "Lionel", "Messi")]);
self.modifiedStudent = ko.computed(function(){
return ko.utils.arrayFilter(self.students(), function(student) {
return student.hasChanged();
});
}, self);
self.Name = ko.observable("Programming 101");
}
$(document).ready(function () {
var myViewModel = new course();
ko.applyBindings(myViewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
List of all students:
<div data-bind="foreach: students">
<div>
<span data-bind="text: studentId"></span>
<input type="text" data-bind="value: firstName" />
<input type="text" data-bind="value: lastName" />
</div>
</div>
<br/>
List of students which has been modified:
<div data-bind="foreach: modifiedStudent">
<div>
<span data-bind="text: studentId"></span>
<input type="text" data-bind="value: firstName" readonly />
<input type="text" data-bind="value: lastName" readonly />
</div>
</div>

angularjs clean input field after submission

trying to clear input filed after button is clicked and post saved with angular but it does not work. here is a simple code
<!--html-->
<input type="text" ng-model="addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.addField = '';
function addPost(item) {
/*code for adding*/
$scope.addField = "";
}
Use a object instead of string, Try this
<!--html-->
<input type="text" ng-model="form.addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.form = {};
$scope.addPost = function(item) {
/*code for adding*/
$scope.form = {};
}

Pass Multiple values via AJAX

I am stuck in passing the multiple value through AJAX call in Codeigniter.
My View is :
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone()
.find("input:text").val("").end();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
$('input', newElement).attr("id", id );
newElement.appendTo($("#elements"));
if($('#elements').find('div').length=='5')
{
$('#btn').prop('disabled',true);
}
}
$('#exercises').on('click', '.remove', function() {
if($('#elements').find('div').length<'6')
{
$('#btn').prop('disabled',false);
}
if($('#elements').find('div').length=='1')
{
$('.remove').addAttr("disabled",true);
}
$(this).parent().remove();
return false; //prevent form submission
});
});
</script>
/******************************
<script>
var base_url = '<?=base_url()?>';
$(document).ready(function()
{
$('#Edit').click(function()
{
$('#Name').removeAttr("disabled");
});
$('#Add').click(function()
{
$('#Name').attr("disabled","disabled");
$('#Phone').attr("disabled","disabled");
$('#email').attr("disabled","disabled");
$('#CurrentlyLocated').attr("disabled","disabled");
$('#KeySkills').attr("disabled","disabled");
//var queryString = $('#form1').serialize();
$.ajax({
url: '<?php echo site_url('PutArtistProfile_c/formDataSubmit');?>',
type : 'POST', //the way you want to send datas to your URL
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
success : function(data)
{ //probably this request will return anything, it'll be put in var "data"
$('body').html(data);
}
});
});
});
</script>
<p>
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" id="00" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
<div id="count"></div>
<input type="button" id="btn" value="Add Audio"></button>
</p>
My Controller is :
public function formDataSubmit()
{
$queryAudio1 = $this->input->post('Audio1');
$queryAudio2 = $this->input->post('Audio2');
$queryAudio3 = $this->input->post('Audio3');
$queryAudio4 = $this->input->post('Audio4');
$queryAudio5 = $this->input->post('Audio5');
}
How can I pass Multiple Values of text box? The above code is passing the values to the controller. But on clicking 'x' Button the value of text box is been getting deleted, but the id of the textbox is getting Incremented, Thus I am not able to pass the further values of textbox to controller via AJAX. Please help me over here.
instead of doing :
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
You can do as
data:$("#Form_id").serialize(); // all form data will be passed to controller as Post data.
If you have a remove button then getting the value by id may result in a js error, Why don't you make use of html element array:
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" name="audio[]" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
IT is very simple:
Consider you want to pass: user name, surname, and country. These are
three input boxes then:
using Jquery do so:
Javascript side
$.post("url",{name:name,surname:surname,country:country},
function(data){
console.log("Query success");
});
In your Model or controller where your Query will be handled
$name=$this->input->post("name");
$surname=$this->input->post("surname");
$country=$this->input->post("country");
in your case just pass parameters that YOU need. I use codignitter and
this method works fine!

Pass Button id to MVC Controller from View

I have a button in my .cshtml page.
I want to pass the id of the button to the controller action.
Here is what I have currently:
#foreach (var item in Model)
{
<div id="report">#Html.ActionLink(#item.Name, "Parameterize", "Report", new { Id = #item.Id }, null )</div><br /><br />
<input id="#item.Id" type="button" onclick="Test()" class="button1" value="Update" />
}
In Firebug I can see that the id is properly fetched:
Now in the js code, here is what I am trying, but for some reason the id is still null in the controller action:
<script type="text/javascript">
function Test() {
var itemId = $('#report').attr('id');
var url = '#Url.Action("UpdateReport/", "Report")';
var data = { Id:itemId };
$.post(url, data, function (result) {
var id = '#postedFor' + postId;
$(id).html(result);
});
}
</script>
In the controller action I have this, and the id is null at this time:
public ActionResult UpdateReport(string id)
{
return View("Index");
}
Every advice is more then welcome.
Thanks in advance, Laziale
You're generating many <div> elements with exactly the same "id" value. The "id" of an element must be unique on the whole page, or else weird things will happen.
Thus, $('#report') is not going to work properly. Maybe you could do:
#foreach (var item in Model)
{
<div id="report_#item.Id">#Html.ActionLink(#item.Name, "Parameterize", "Report", new { Id = #item.Id }, null )</div><br /><br />
<input id="#item.Id" type="button" onclick="Test()" class="button1" value="Update" />
}
Alternatively, you could pass the input element directly to the handler:
<input id="#item.Id" type="button" onclick="Test(this)" class="button1" value="Update" />
Then:
function Test(item) {
var itemId = item.id,
var url = '#Url.Action("UpdateReport/", "Report")';
var data = { Id:itemId };
$.post(url, data, function (result) {
var id = '#postedFor' + postId;
$(id).html(result);
});
}
This line:
var itemId = $('#report').attr('id');
is fetching the id of your div with the id report.
You want to pass the button to the function test() and use it to get its id:
<input id="#item.Id" type="button" onclick="Test(this)" ...
And then in your js Test() function:
var itemId = $(this).attr('Id');
Also note, that the attribute names are case sensitive. You wrote "id", but your attribute is called "Id".
Your selector looks off:
var itemId = $('#report').attr('id');
That is going to get the id value of an element with an id of report. I don't think that's what you're looking for.

Categories

Resources