Input submit only working after second click - javascript

I've created the following form that allows uploading pictures, it has a submit button that is not working fine on IE (it only submits after the second click):
<fieldset id="form-fieldset" data-listurl="#Url.Action("Index", "Partners", new { Area = "Panel" })">
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Logo)
</div>
<div class="editor-field">
#if (ViewData["Logo"] != null && !String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()) && File.Exists(Server.MapPath("~/Content/uploads/" + ViewData["Logo"])))
{
<img src="#Url.Content("~/Content/uploads/" + ViewData["Logo"])" style="max-height: 150px" />
}
<div id="file-upload">
<span class="input-xlarge uneditable-input">#(ViewData["Logo"] == null || String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()) ? "No files selected" : ViewData["Logo"].ToString()) </span><input type="button" class="btn btn-primary select-button" value="Selecionar" /><input type="button" class="btn remove-button" value="Remover" />
<input type="file" name="image" id="image" style="visibility: hidden" />
</div>#Html.HiddenFor(model => model.Logo)
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Salvar" />
<input type="button" class="btn" id="btnCancel" value="Cancelar" />
</div>
The form above has a button to open the file dialog, instead of displaying the normal input file control.
I use the following script to open the file dialog and set a span tag content to the filename.
<script type="text/javascript">
$(document).ready(function () {
$('#btnCancel').click(function () {
location.href = $('#form-fieldset').data('listurl');
});
$('#file-upload .select-button').click(function () {
$('#file-upload input[type=file]').click();
});
$('#file-upload input[type=file]').change(function () {
var entireValue = $("#file-upload input[type=file]").val();
var fileNameOnly = entireValue.substring(entireValue.lastIndexOf('\\') + 1, entireValue.length);
$("#file-upload span").html(fileNameOnly);
});
$('.remove-button').click(function () {
$('#file-upload span').html('No files selected');
$('#file-upload input[type=file]').val('');
});
});
</script>
The problem happens only on IE (I've tested only on IE10). Firefox and Chrome works perfectly.

Related

Html.BeginForm not submitting when using .trigger('submit')

So I'm using razor views and JS/jQuery. I have a form that I simply cannot get to work the way I need it to. Based on my debugging, I'm just not hitting the controller at all. I think the form is just never actually submitting. I feel like the solution below should help, but I just dont understand why it isnt. Any help would be greatly appreciated.
<script language="javascript" type="text/javascript">
function CheckSubmit() {
// do some stuff
$('#myForm').trigger('submit');
return true;
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
</script>
<div id="stuff" style="display: none">
<div id="otherStuff">
#using (Html.BeginForm("MyControllerMethod", "MyController", FormMethod.Post, new { id = "myForm" }))
{
#Html.HiddenFor(x => x.UserItem.UserId)
#Html.HiddenFor(x => x.UserCert.CertificateSubject)
#Html.HiddenFor(x => x.comments)
#Html.HiddenFor(x => x.IsReactivationRequest)
<div>
<a id="btnHideDetails">
<span>Close</span>
</a>
</div>
// displays some information
<div style="padding-bottom: 15px">
#Html.RadioButtonFor(x => x.radioBtnValue, "approve")Approve <br />
#Html.RadioButtonFor(x => x.radioBtnValue, "reject")Reject <br />
</div>
<div id="txtComments" style="display: none; padding-bottom: 15px;">
<div>Comments:</div>
<div>
#(Html.TextArea("commentBox", new { maxlength = 2000, cols = 70, rows = 5 }))
</div>
</div>
}
</div>
<div>
<div id="btnSubmitDiv" style="display: none;">
<input id="btnSubmit" onclick="return CheckSubmit();" type="submit" value="Submit"/>
</div>
</div>
</div>
Right now all of the js is contained in the cshtml file. I know there are other ways of submitting this form, but for some reason this specific solution is not working and I need to understand why. Thank you!
I use the following code,and it can work:
View:
<div id="stuff" >
<div id="otherStuff">
#using (Html.BeginForm("TestJquery", "Test", FormMethod.Post, new { id = "myForm" }))
{
<input name="UserId" />
<div>
<a id="btnHideDetails">
<span>Close</span>
</a>
</div>
// displays some information
<div style="padding-bottom: 15px">
</div>
<div id="txtComments" style="display: none; padding-bottom: 15px;">
<div>Comments:</div>
<div>
#(Html.TextArea("commentBox", new { maxlength = 2000, cols = 70, rows = 5 }))
</div>
</div>
}
</div>
<div>
<div id="btnSubmitDiv">
<input id="btnSubmit" onclick="CheckSubmit()" type="button" value="Submit" />
</div>
</div>
</div>
js:
<script language="javascript" type="text/javascript">
function CheckSubmit() {
// do some stuff
$('#myForm').trigger('submit');
}
</script>
action:
[HttpGet]
public IActionResult TestJquery() {
return View();
}
[HttpPost]
public IActionResult TestJquery(string UserId)
{
return View();
}
result:

Laravel - Image File Uploader submits save button instead of uploading image

I am using Laravel-5.8 for my project. I want to upload image, and click on submit button to save the image and other text fields into the database.
Controller
public function create()
{
$countries = ConfigCountries::all();
return view('organization.companies.create')->with('countries', $countries);
}
public function store(Request $request)
{
try {
$orgStartDate = Carbon::parse($request->org_start_date);
$arr = [
'organisation_code' => $request->organisation_code,
'organisation_name' => $request->organisation_name,
'website' => $request->website,
'org_decription' => $request->org_description,
'total_employees' => $request->total_employees,
'registration_number' => $request->registration_number,
'org_start_date' => $request->$orgStartDate,
'phone_number' => $request->phone_number,
'secondary_phone' => $request->secondary_phone,
'email' => $request->email,
'secondary_email' => $request->secondary_email,
'address1' => $request->address1,
'address2' => $request->address2,
'country_id' => $request->country_id,
'created_by' => Auth::user()->id,
'created_at' => date("Y-m-d H:i:s"),
'is_active' => 1,
];
if ($request->org_image != "") {
$org_image = time() . '_' . $request->org_image->getClientOriginalName();
$request->org_image->move('storage_files/companies/profile/', $org_image);
$arr['org_image'] = 'storage_files/companies/profile/' . $org_image;
}
$company = OrgCompany::create($arr);
$company->save();
Session::flash('success', 'Company is created successfully');
return redirect()->route('organization.companies.index');
} catch (Exception $exception) {
return back()->withInput()
->withErrors(['unexpected_error' => 'Unexpected error occurred while trying to process your request.']);
}
}
view
<div class="card-body">
<form action="{{ route("organization.companies.store") }}" method="post class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="text-center">
<input type="image" class="profile-user-img img-fluid img-circle"
src="{{asset('theme/adminlte3/dist/img/company_logo.png')}}"
id="wizardPicturePreview" title="" width="150">
<input type="file" name="picture" id="wizard-picture" class="" hidden>
<h4 class="profile-username text-center">Click On Image to Add Logo</h4>
</div>
<span style="color:blue;"><h4 class="box-title"><b>Contact Information</b></h4></span>
<hr class="m-t-0 m-b-40">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Phone No.</label>
<div class="col-md-9 controls">
<input type="text" name="phone_number" placeholder="Enter Company Phone no. here" class="form-control" value="{{old('phone_number')}}">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Alternative Phone No.</label>
<div class="col-md-9 controls">
<input type="text" name="secondary_phone" placeholder="Enter Alternative Phone no. here" class="form-control" value="{{old('secondary_phone')}}">
</div>
</div>
</div>
<!--/span-->
</div>
<hr>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-primary">Add Company</button>
<button type="button" onclick="window.location.href='{{route('organization.companies.index')}}'" class="btn btn-default">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#wizard-picture").change(function(){
readURL(this);
});
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview').attr('src', e.target.result).fadeIn('slow');
}
reader.readAsDataURL(input.files[0]);
} }
$("input[type='image']").click(function() {
$("input[id='wizard-picture']").click();
});
$(".form-control").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
return false;
}
});
</script>
The issue is that without clicking on the save submit button, when I clicked on image file uploader, it redirects to the index page without uploading the image to the screen.
How do I resolve this?
Thanks
An input type of image is a way to define an image as a submit button, so clicking on the image actually is submitting the form. You can either change the image to a regular <img> tag or change you click handler to prevent the default action like so
$("input[type='image']").click(function(e) {
e.preventDefault();
$("input[id='wizard-picture']").click();
});
Also just a heads up, you have a typo in the line that opens your form. There's no closing quotes after method="POST which is probably why the page is just redirecting on submit
Maybe because the closing quote of method is missing in <form> starting tag

Remove cloned div one by one from last but not the default one using jquery in MVC 5

My default view is this.
Add button is working as expected but when I try to remove the cloned div I am only able to remove the last one but not all the cloned div one by one from last expect the default one.
Here is my Div and Jquery to add and remove div.
Add:
$("#AddSubService").click(function(){
$("#SubServices").append($('#SubServiceName').clone(true).find("input").val("").end());
$("#SubServices").append($('#SubServiceDescription').clone(true).find("input").val("").end());
});
Remove:
$("#RemoveSubService").click(function(e){
$("#SubServices").children("div[id=SubServiceDescription]:last").fadeOut();
$("#SubServices").children("div[id=SubServiceName]:last").fadeOut();
});
Div:
<div id="SubServices">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<h2>Sub Services</h2>
<input type="button" value="Add" class="btn btn-default" id="AddSubService" /> |
<input type="button" value="Remove" class="btn btn-default" id="RemoveSubService" />
</div>
</div>
<div class="form-group" id="SubServiceName">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="SubServiceDescription">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
As I am pretty new in MVC and Jquery so any right direction to achieve the same would be highly appreciable.
Use below script function to remove cloned divs
$("#RemoveSubService").click(function (e) {
var divCount = $("#SubServices").children("div[id=SubServiceDescription]").length;
while (divCount > 1) // comparing with 1 beacuse: It will keep default div and remove rest
{
$("#SubServices").children("div[id=SubServiceDescription]:last").remove();
$("#SubServices").children("div[id=SubServiceName]:last").remove();
divCount--;
}
});
This is not happening correct because of id attribute, id attribute should always be unique in html that'w why, use class instead of.
$(document).ready(function() {
$('.AddNew').click(function() {
$(".TargetElements:first").clone().insertAfter('.TargetElements:last');
$('.Remove').show();
});
});
$(document).ready(function () {
$('.Remove').click(function () {
if ($(".TargetElements").length > 1) {
$(".TargetElements:last").remove();
}
else {
$('.Remove').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="TargetElements">
<label>Name</label> </div>
<div>
<input type="button" value="Add" class="AddNew" />
<input type="button" value="Remove" class="Remove" hidden="hidden" />
</div>
<div class="TargetElements">
<label>Name</label>
</div>
<div> <input type="button" value="Add New Language" class="AddNew" />
<input type="button" value="Remove" class="Remove" hidden="hidden" />
</div>
<script>
$(document).ready(function () {
$('.AddNew').click(function () {
$(".TargetElements:first").clone().insertAfter('.TargetElements:last');
$('.Remove').show();
});
});
</script>
<script>
$(document).ready(function () {
$('.Remove').click(function () {
if ($(".TargetElements").length > 1) {
$(".TargetElements:last").remove();
}
else {
$('.Remove').hide();
}
});
});
</script>

How to fill only one textbox from a modal when you have a lot of them

I explain my issue, i have this code :
#Html.LabelFor(m => m.X.Y, new { #class = "col-sm-d col-sm-2 control-label" })
<div class="col-sm-2">
#Html.TextBoxFor(m => m.X.Y, new { #class = "form-control", #id = "X"})
</div>
<div class="col-sm-2">
#Html.EnumDropDownListFor(m => m.X.Y, new { #class = "form-control", #id = "Dropdown1" })
</div>
#Html.LabelFor(m => m.X.Y, new { #class = "col-sm-d col-sm-2 control-label" })
<div class="col-sm-2">
#Html.TextBoxFor(m => m.X.Y, new { #class = "form-control", #id = "X_Y2"})
</div>
<div class="col-sm-2">
#Html.EnumDropDownListFor(m => m.X.Y, new { #class = "form-control", #id = "Dropdown2" })
</div>
This modal :
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Multiples
</div>
<div class="modal-body">
Valeur <input style="text-align:right;" type="text" id="Valeur"/><br />
Unité <input style="text-align:right;" type="text" id="Unite1" /><br />
Unité <input style="text-align:right;" type="text" id="Unite2" /><br />
Opérant (+) <input style="text-align:right;" type="text" id="Operand" /><br />
<br />
Valeur <input style="text-align:right;" type="text" id="Valeur2" /><br />
Unité <input style="text-align:right;" type="text" id="Unite3" /><br />
Unité <input style="text-align:right;" type="text" id="Unite4" /><br />
Opérant (+) <input style="text-align:right;" type="text" id="Operand2" /><br />
<br />
Valeur <input style="text-align:right;" type="text" id="Valeur3" /><br />
Unité <input style="text-align:right;" type="text" id="Unite5" /><br />
Unité <input style="text-align:right;" type="text" id="Unite6" /><br />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">
Annuler
</button>
<button type="button" class="btn btn-success" data-dismiss="modal" id="valueOK">
Valider
</button>
</div>
</div>
</div>
</div>
And my scripts :
$(function () {
$("#Dropdown1,#Dropdown2,#Dropdown3,#Dropdown4,#Dropdown5,#Dropdown6,#Dropdown7,#Dropdown8,#Dropdown9,#Dropdown10,#Dropdown11,#Dropdown12,#Dropdown13,#Dropdown14,#Dropdown15,#Dropdown16,#Dropdown17,#Dropdown18,#Dropdown19,#Dropdown20,#Dropdown21,#Dropdown22,#Dropdown23,#Dropdown24,#Dropdown25,#Dropdown26,#Dropdown27,#Dropdown28,#Dropdown27,#Dropdown28,#Dropdown29,#Dropdown30,#Dropdown31,#Dropdown32,#Dropdown33,#Dropdown34,#Dropdown35,#Dropdown36,#Dropdown37").change(function () {
//Recupere la value de la liste
selection = $(this).val();
//Mettre la valeur du choix de liste.
if (selection == 10) {
//Affiche le modal
$('#myModal').modal('show');
}
});
});
var modalValue1 = $('#Valeur')
var modalValue2 = $('#Unite1')
var modalValue3 = $('#Unite2')
var modalOperand = $('#Operand')
var modalValue4 = $('#Valeur2')
var modalValue5 = $('#Unite3')
var modalValue6 = $('#Unite4')
var modalOperand2 = $('#Operand2')
var modalValue7 = $('#Valeur3')
var modalValue8 = $('#Unite5')
var modalValue9 = $('#Unite6')
$('#valueOK').click(function () {
$('#X').val(modalValue1.val() + modalValue2.val() + modalValue3.val() + modalOperand.val() + modalValue4.val() + modalValue5.val() + modalValue6.val() + modalOperand2.val() + modalValue7.val() + modalValue8.val() + modalValue9.val());
})
So that works pretty fine, when i put text in my textbox and after I press the button the information are going into the texbox in my page, that's ok. But if i try to apply this to other textboxes i have i'm facing a problem, if i fill the modal it will take this information and put it into every textbox of the page, but thats not what i want, how can i do for example to fill the first textbox with information and the second one with other information ?
if I understand what you want, you have lots of textbox and dropdown , if any one of the dropdownlist changed to 10 you want to show a dialog and after that fill the related textbox.
so, you coded too hard.
firstly, use class selector instead id selector $("#DropDown1,#DropDown2,....") -> $(".MyDropdown")
after that you can control you modal
for finding the nearest textbox you use closet or parent command in jquery.
it's just a solution, you can find lots of another solution to do that. like finding by data- Or aria- .
i hope it will be useful for you.
EDIT
$(".dropdown").click(function(){
var targetTextBox=$(this).closest("div+ input").prev().find('input');
BootstrapDialog.show({
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': 'remote.html'
},
buttons: [{
id: 'btn-1',
label: 'Click to disable and spin.',
action: function(dialog) {
targetTextbox='load your data';
}
}]
});
});
this is an example, but you have to custom it for you.
and you have to use dialog box instead of modal

retrieve the model property value

I have following form
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
I want to get this model properties using jquery or javascript
for that I just followed approach like below
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
<div id="testid" class="col-md-offset-2 col-md-10" >
<input type="button" value="Test" class="btn btn-default" />
</div>
</div>
}
then in javascipt
<script type="text/javascript">
$(document).ready(function () {
var sampleID;
$("#Product_ID").keyup(function () {
sampleID = $('#Product_ID').val();
});
$('#testid').click(function () {
alert(sampleID);
});
});
</script>
But seems like this is not optimum approach me , keyup
appreciate if can suggest good way to get these values once after courser out
You can get value of #Product_ID in click event of #testid using $('#Product_ID').val() like below.
$('#testid').click(function () {
alert($('#Product_ID').val());
});
Since you are using razor then you can use # to get it directly in jquery like so:
$(function() {
var sampleID = "#Model.Product_ID";
});
The model is server-side only. If you need to do something with the values in the view, you handle it as if it's a regular HTML page and javascript.
If you want to grab the value of an input field, use the blur event that is triggered when focus is lost.
$("#Product_ID").blur(function() {
alert( "Handler for .blur() called." );
});
It looks like a typo in your JS. change kepup it to keyup.
This should work as expected.
$("#Product_ID").keyup(function () {
sampleID = $('#Product_ID').val();alert(sampleID);
//or you can use
alert($(this).val());
});

Categories