input hidden value doesn't send to controller - javascript

I'm trying post to my database,everything what i want i can get from my formcollection and my table but input hidden value.My main view is using #model List
Here is my code this my modal popup
#using (Html.BeginForm("update3", "UpdateInfo", FormMethod.Post))
{
<div class="modal fade" role="dialog" id="mymodal">
<form id="stok_formu">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modal2">
<div class="row">
<label for="names" id="name" name="name"></label>
<input type="hidden" id="names" name="names" />
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label(" Clothes codes: ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="codes" name="codes" />
</div>
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label("New Price : ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="newprice" name="newprice" />
</div>
</div>
<input class="btn btn-success" id="change" type = "submit" name="change"/>
</div>
</div>
</div>
</form>
</div>
}
With this javascript code ,i can get my "name" from my table and put on my modal and my problem is begin is here,when i click button submit modal popup doesn't send hidden value to controller but ican get my value of "newprice"
function metot(x) {
namee = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = namee;
}
and table from my main view
<tbody id="tablo2">
#foreach(var oge in Model)
{
<tr onclick="metot(this)">
<td>#Html.Encode(oge.name)</td>
<td id="codes">#Html.Encode(oge.codes)</td>
<td id="price">#Html.Encode(oge.price)</td>
<td>
<button id="change" onclick="metot(this)" type="button" data-toggle="modal" data-target="#mymodal" class="btn btn-warning tab-content"><span>Change</span></button>
</td>
</tr>
}
</tbody>

You are setting the text of the label with id name, but you aren't setting the value of the hidden field with id names, hence it is not sent when you submit the form. <label> elements do not send data back to the server.
This should work (I assume the variable namee should actually be called urun_adi):
function metot(x) {
urun_adi = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = urun_adi;
document.getElementById("names").value = urun_adi;
}

Related

Javascript function works only on the first table row inside my foreach laravel loop

I am using a javascript functions to input a number and automatically display the result after calculation inside a boostrap modal.
If click the request button at the first row, javascript functions work well. But when I click on the request button on the second row and succeeding rows, it doesn't function.
I am not really sure if the problem is the data inside the modal or the data outside the modal
I tried to getElementsByClassName instead of ID but it still not working.
<script>
function mult(value) { // === calculate the profit and the total amount due === //
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit").value = x;
document.getElementById("total").value = y;
}
</script>
<table id="table1">
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Requests</th>
</tr>
</thead>
<tbody>
#foreach($Clients as $Client)
<tr id="foreach-row">
<td>{{ $Client->full_name }}</td>
<td>
<div class="buttons">
<a class="btn icon btn-secondary" data-toggle="modal"
data-target="#LoanRequestModel-{{ $Client->id }}">
Request
</a>
</div>
</td>
</tr>
{{-- =========== MODEL - NEW REQUEST ===============--}}
<div class="modal" id="LoanRequestModel-{{ $Client->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>REQUEST</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.storeRequest', $Client->id) }}" method="post"
class="loanrequest_form" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Full name</label>
<div class="form-group">
<input type="text" name="creditor_full_name"
class="form-control" value="{{ $Client->full_name }}" >
</div>
<div>
<label>Amount</label>
<div class="form-group">
<input type="number" name="loan_amount"
class="form-control" onkeyup="mult(this.value);" >
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Interest Rate</label>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Choose</label>
<select class="form-select rate"name="interest_rate" >
<option value="15" selected>15%</option>
<option value="20">20%</option>
</select>
</div>
</div>
<div class="col-md-7">
<label>Profit</label>
<div class="input-group mb-3">
<input type="text" id="profit" class="form-control" name="profit"
aria-label="Amount">
</div>
</div>
</div>
<div class="row">
<label>Total Amount due</label>
<div class="input-group mb-3">
<input type="text" id="total" class="form-control" name="amount_due"
aria-label="Amount">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endforeach
</tbody>
</table>
The problem - as others have said above - is that whilst you are making the ID of each modal unique using :
id="LoanRequestModel-{{ $Client->id }}"
within your loop, when generating each modal, you are using fields which have non-unique IDs :
type="text" id="profit"
type="text" id="total"
What you would be better off is making those IDs non-unique, in the same way that you did with the modal ID :
type="text" id="profit-{{ $Client->id }}"
type="text" id="total-{{ $Client->id }}"
and add IDs to the fields which you will need to use in your script that does not presently have one :
type="number" id="loan_amount-{{ $Client->id}}" name="loan_amount"
Then, when you trigger the javascript on keyup here :
onkeyup="mult(this.value);"
rather than pass the value of the field, pass the client ID :
onkeyup="mult({{ $Client->id);"
Then you just need to adjust your javascript (because it's no longer being passed the loan_amount) so that it first gets the loan_amount, then the other bits and pieces it needs, and finally returns them to the right place :
<script>
function mult(id) { // === this is now receiving the ID, not a value so first we need to get the value for the relevant field *emphasized text*== //
var value = document.getElementById("loan_amount-" + id).value
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit" + id).value = x;
document.getElementById("total" + id).value = y;
}
</script>

What's the correct way to submit a single element in a list when each of them has a separate submit button

I have an event page which contains a list of participants. From there users can be invited to that event by opening a modal view containing a user list. Users are shown in the same modal with each having an 'Invite'(submit) button next to them. How can I let the controller action know which user is invited?
From what I could find, creating a form for each list element is bad and in addition displays warnings, but if I create a form element on top of the 'foreach', I then need to somehow find which user to submit.
Also thought about appending incrementing numbers to each of submit button name, but I still need to somehow map them to 'their' users.
Along with the invited user id, controller post action also needs to receive the event id.
Here's the code:
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" />
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
completed = () => {
alert("User invited");
};
</script>
You can use jquery ajax to pass the parameters you need, through the click event, get the corresponding value of the control needed next to the current button.
By adding the name attribute to the submit button, and then triggered in jquery.
And add the id to the div that stores the Text value of User to facilitate finding the corresponding value in jquery.
#section Scripts{
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$("[name=submitBtn]").click(function () {
event.preventDefault();
var obj = {
myUser: {
Text: $($(this).parent().siblings()[0]).text(),
Value: $($(this).parent().siblings()[1]).val()
},
eventId: $("#Invitation_FkEvent").val()
};
$.ajax({
url: $("#eventMemberForm").attr("data-ajax-url"),
method: 'post',
data: obj,
})
});
});
completed = () => {
alert("User invited");
};
</script>
}
<h1>Index</h1>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary">Submit</button>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div id="textValue"> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" name="submitBtn"/>
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
Controller:
public IActionResult SendInvitation(User myUser, string eventId)
{
//do what you want
return View();
}

How to create a simple edit button on crud?

i'm trying to make a simple Crud for my homework . most of my code works properly for the most part, except the edit button. it only edits the first row. below, i provide my TS code along with my HTML. for the HTML i'm using Modal windows. so everytime i click on the edit buttons. a modal will appears
function create() {
let user: string = String($("#username").val());
let data: JQuery = $("<tr id='crudData'><td>" + user + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crud").append(data);
}
function edit() {
let user2: string = String($("#username2").val());
let data2: JQuery = $("<tr id='crudData'><td>" + user2 + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crudData").replaceWith(data2);
}
$("#userbstg").on("click", create);
$("#saveEdit").on("click", edit);
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3 class="section-heading">Aufgabe - Usermanager</h3>
<label for="username">Username:</label>
<input id="username" class="form-control col-md-3" type="text">
<button id="userbstg" class="btn btn-info">Add</button>
<table id="crud" class="col-md-4 table">
<tr>
<th class="col-2" id="user">User</th>
<th class="col-2" id="edit"></th>
</tr>
</table>
</div>
</div>
</div>
<div class="modal fade" id="crudModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<label for="username2">Username:</label>
<input id="username2" class="form-control col-md-12" type="text">
<button type="button" id="saveEdit" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</section>

show the sucess popup after form submit form?

Here i added one form with data model in codeigniter views page
<a class="handCursor " href="javascript:void(0)" id="franchise">Franchisee </a>
<!-- Modal -->
<div class="modal fade" id="franchisee_signup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo base_url();?>general/general_form" method="POST" name="signup">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><i class="fa fa-desktop"></i> Request For Franchisee Program</h4>
</div>
<div style="clear: both;"></div>
<div class="modal-body clearfix">
<div class="bk_lft" style="width:100%;">
<div class="bk_gr" style="width:100% !important">
<div class="contact_form2">
<div class="bk_roominfo">
<div class="clearfix"></div>
<div class="frm_clmn">
<label>First Name: <em style="color:#F00;">*</em></label>
<input name="first_name" id="txt_name" type="text">
<input name="form_type" id="company_name" type="hidden" value="franchise">
</div>
<div class="frm_clmn1">
<label>Last Name: <em style="color:#F00;">*</em></label>
<input name="last_name" id="txt_lname" type="text">
</div>
<div class="frm_clmn">
<label>Phone: <em style="color:#F00;">*</em></label>
<input name="mobile" id="txt_mobile" type="text">
</div>
<div class="frm_clmn1">
<label>Email: <em style="color:#F00;">*</em></label>
<input name="email" id="txt_email" type="text">
</div>
<div class="frm_clmn1" style="width:100%;">
<label>Message:<em style="color:#F00;">*</em></label>
<textarea name="message" id="txt_message" cols="" rows="" style="resize:none;"></textarea>
</div>
<div class="bk_bt" style="float:left; margin-top:12px;">
<button type="submit" name="send_contact_enq" id="send_contact_enq" value="Continue" style="float:left;">Send</button>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
This is the form and we add the insert query in controller
public function general_form()
{
$post = $this->input->post();
unset($post['send_contact_enq']);
$insert_id = $this->custom_db->insert_record('corporate_form_reqlist',$post);
redirect(base_url()."general/index");
}
after submitting the form while inserting into db and we redirect to front page . we need before redirect from controllers is there is any possible to show the success popup after close the popup message redirect happened .
we tried all my logic which i know but not get the correct response
try passing some value as param and give success message by checking that in redirected page..
redirect(base_url()."general/index?status=success");
and in general/index file
if(isset($_GET['status']) && $_GET['status'] == "success"){
echo "Successfull Message";
}
if($insert_id=='success'){//change success based on the returned value of the model
echo "<script>
alert('Success');
window.location.href='".base_url('general/index')."';
</script>";
}
You can use ajax function for your form that will send data to PHP to execute general_form tasks without redirecting. PHP returns true if successfully inserts record to db and javascript then triggers alert() or prompt() and windows.location = "your redirection link"

How to specify separate contact scripts for different buttons

I am trying to point my scripts to two different buttons in my html. The scripts both send an email of what the customer entered however both belong to two separate modal forms.
The first form is:
!-- Beginning of Pop-up Device Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-1"></div>
<div class="modal fade" id="modal-1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Device Testing</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Device and Meter Testing" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
The script that I have associated with this modal form is:
<script type="text/javascript">
$(document).ready(function() {
$('#emailForm').on('submit', function(event) {
event.preventDefault();
if( ! $("form")[0].checkValidity() ) {
return false;
}
// Disable the submit button
$('#contactSubmit').attr("disabled", "disabled");
$('#contactSpinner').css('display', 'inline-block');
$.ajax({
type : "POST", cache: false,
url : "#controllers.routes.Application.contactSend()",
data : {
contactName: $("#contactName").val(),
contactEmail: $("#contactEmail").val(),
contactMessage: encodeURIComponent( $("#contactMessage").val() ),
contactType: $("#contactType").val()
},
success : function(msg) {
// Check to see if the mail was successfully sent
if (msg == 'OK_SO_UPDATE') {
$("#messageSuccess").css("display", "block");
}
},
error : function(ob, errStr) {
$("#messageError").css("display", "block");
$("#messageError span.message").text(ob.responseText);
},
complete: function() {
$('#contactSubmit').removeAttr("disabled");
$('#contactSpinner').css('display', 'none');
}
});
return false;
});
});
</script>
This is referencing the scripts by giving the my form an id of "emailForm". However, if I wanted to add a second modal form such as:
<!-- Beginning of Pop-up Professional Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-2"></div>
<div class="modal fade" id="modal-2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Professional</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Professional" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
This references the same script since I gave this form the id of emailForm as well. However, for some reason the alerts that are suppose to appear for the second form are not showing up. Any idea what this could be? Will I need to create a unique script for each form?
Duplicate ID's violate the specifications and are problematic, but here's a way around that to temporarily repair this code.
$(event.target).find("#messageError").css("display", "block");
The FORM tag is also malformed. I moved it up to match the bottom form tag (to after the fourth DIV).
(There are many duplicate ID problems yet unresolved, but the above specifies to the program within the event listener which element to reveal.)
The solution is to use class and name attributes where appropriate.
JSFiddle: http://jsfiddle.net/BloodyKnuckles/s7D98/

Categories

Resources