Pass Button id to MVC Controller from View - javascript

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.

Related

Get Parent form Id of a Button using Javascript

I have next buttons in my page. each button are under a form. when next button click i want to pass value.these value may change based on a form. i have tried this code but it cant pass diffrent value.
Button
<input class="btn btn-danger next child" type="button" value="Next">
jquery code is.
$('.child').click(function(){
var id=$(this).parents('form:eq(0)').attr('id');
let myForm = document.getElementById(id);
let formData = new FormData(myForm);
for (var value of formData.values()) {
console.log(value);
}
});
i want like this
<input class="btn btn-danger next child" type="button" value="Next" onClick="next(id,1)">
how to write function to access parent of this form?
Please try
$('.child').click(function(){
var id=$(this).closest('form').attr('id');
let myForm = document.getElementById(id);
let formData = new FormData(myForm);
for (var value of formData.values()) {
console.log(value);
}
});

Mapping not working in knockout with the button click

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>

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

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!

How can I populate an input field with a .val()?

I'm trying to edit list items that I have and I want to set the text of the parent section to the form field with .val(). I also want to remove it from the local storage as well, problem is I have no idea how to do this and it doesn't seem to be to popular online because I can't find it anywhere.
This is how I'm bringing in the data through the input form:
function addTodo(form) {
var input = $(form).find('input[name="todo"]').first();
if (input) {
var todo = input.val();
if (Modernizr.localstorage) {
var todo_list = {};
if (localStorage.todos) {
todo_list = JSON.parse(localStorage.todos);
}
var id = +new Date;
todo_list[id] = {
name: todo,
completed: false
};
localStorage.todos = JSON.stringify(todo_list);
drawTodos();
}
input.val('');
}
if ( jQuery.fn.validate ) {
$(form).validate().resetForm();
}
}
How would I select a list item that I've added so that it will end up back in the input feild so I can edit it?
<section>
<h1>List</h1>
</section>
<section id="todo_list">
<header>
<form>
<input type="text" name="todo" placeholder="What do you need to do?" />
<input type="submit" name="add_todo" value="Add To List" />
</form>
</header>
</section>
I have some html generating in a loop within the jquery:
<section class="todo_item" id="item' + id + '"><span id="complete" class="colour complete">Complete</span><span id="incomplete" class="colour incomplete">Incomplete</span><span class="content editable" id="done">' + todo.name + '</span><img src="img/delete.png" /></section>
Why don't you attach a handler to the span that has editable class?
Something like this:
$(document).ready(function () {
$(".content.editable").click(function () {
$("input[name='todo']").val($(this).text());
});
});
Please note, IDs must be unique. It is an error to assign the same ids: 'done', 'incomplete', 'complete' to several sections.

Categories

Resources