I want to show a form in a modal window but I have my buttons on my javascript, so I would want to make them the "submit button" of the form.
This is my code:
I open the modal with this javascript function, with 2 buttons:
modal.js
window.newModal = function(path, title){
ShopifyApp.Modal.open({
src: path,
title: title,
height: 400,
width: 'large',
buttons: {
primary: {
label: "OK",
message: 'modal_ok',
callback: function(message){
ShopifyApp.Modal.close("ok");
}
},
secondary: {
label: "Cancel",
callback: function(message){
ShopifyApp.Modal.close("cancel");
}
}
},
}, function(result){
if (result == "ok")
ShopifyApp.flashNotice("'Ok' button pressed")
else if (result == "cancel")
ShopifyApp.flashNotice("'Cancel' button pressed")
});
}
And this is my form:
form_page.html.erb
<section>
<section class="full-width" align="center">
<article>
<div class="card" style="margin-bottom:0px;">
<form method="POST" action="form_page">
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
<div class="row">
<label>Dirección:</label>
<input type="text" name="address"/>
</div>
<div class="row">
<label>Apt, suite, etc. (opcional):</label>
<input type="text" name="addressopt"/>
</div>
<div class="row">
<label>Código Postal:</label>
<input type="text" name="postal" pattern="[0-9]{5}"/>
</div>
<div class="row">
<label>Phone (opcional):</label>
<input type="text" pattern="[0-9]{9}" name="phone"/>
</div>
<div class="row">
<label>City:</label>
<select name="city">
<option>Madrid</option>
<option>Barcelona</option>
<option>Málaga</option>
</select>
</div>
</form>
</div>
</article>
How can I submit that form through that function buttons?
I haven't used ShopifyApp ever, but in general if you want to submit a form in javascript you can just call submit() on the element. You'd want to give an id to the form to find it easily.
https://www.w3schools.com/jsref/met_form_submit.asp
Related
Hi i have a class using needs validate in form is there a way for me to validate this on button submit onclick ? or a better way to improve the coding for this ?
Where i can even call the invalid feedback ?
and also when button click it will check the valdiation first before call the database
As this code got some problem later in the end where i couldnt validate anything when button click as it passes to the database immediately without the validation check .
(function validateForm() {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.stopPropagation();
event.preventDefault();
}
form.classList.add('was-validated');
}, false)
})
})();
<form id="form" class="needs-validation" onsubmit="return validateForm()">
<!-- <label id="mandatoryField" class="hiddenfield" hidden>* is mandatory</label> -->
<div class="form-group row nameform">
<label for="validationName" class="col-form-label nameadduser">Name:</label>
<div class="col-6">
<input name="validationName" type="text" class="form-control" id="validationName" placeholder="Name" title="Name can be any. e.g. john" required>
<div class="invalid-feedback">
Enter a Name!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationEmail" class="col-form-label emailadduser">Email:</label>
<div class="col-6">
<input name="validationEmail" type="email" class="form-control emails" id="validationEmail" placeholder="example1#gmail.com" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<div style="margin-left: 3px;" class="invalid-feedback">
Enter a correct Email format!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationUserName" class="col-form-label usernameadduser">Username:</label>
<div class="col-6 ">
<input name="validationUserName" type="text" class="form-control " id="validationUserName" placeholder="Username" pattern="^(?=.{4,}$)(?:[a-zA-Z\d]+(?:[a-zA-Z\d])*)+$" title="Username should be at least 4 letter" required>
<div class="invalid-feedback">
Username must meet the following requirements:
<b>At least four letter</b>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label oldpasswordadduser">Old<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="oldpasswords" placeholder="Password" required>
<i class="bi bi-eye-slash" id="toggleoldPassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" title="Password should be like this. e.g. A123de!123"
required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
<div style="margin-left: 20px;" class="invalid-tooltip">
Password do not match or value is null!
</div>
</div>
</div>
<div id="passwordconfirm"></div>
<div class="form-group row">
<label for="validationRole" class="col-form-label role">Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<div class="form-group row placeholderimage">
<img src="" id="output" width="400" height="400" style="border-radius: 50%;" />
<input id="file-upload-input" type="file" accept="image/*" onchange="encodeImageFileAsURL(event);">
</div>
<button id="submitbtn" type="submit" class="btn-primary submitbutton" disabled>Done</button>
</form>
I have a button onclick where i got my database out when click which is this code it is with sweetalert as well not sure do we need to put the prevent button for validation here ?
$('#submitbtn').click(function() {
//get input value field
var name = $('#validationName').val();
var email = $('#validationEmail').val();
var username = $('#validationUserName').val();
var oldpassword = $('#oldpasswords').val();
var password = $('#passwords').val();
var picture = document.getElementById("output").src;
var role = $('#select-user-role').val();
//making ajax call after this retrieve
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/postWithRawBody",
method: "POST",
contentType: "text/plain;charset=UTF-8",
headers: {
// Generally used for queries that we're planning to use
query: `UserUpdate(,'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','','${formatParamString(password)}','','${formatParamString(role)}')`,
// apikey like oXkPNt3p6cuDobzBVjpsPUyawSYDFqFHVWPkijXZZstjVPLLWo
"Content-Type": "text/plain",
apikey: sessionStorage.getItem("apikey")
},
dataType: "text",
// May be quite long
// Usually an array
// Only for specific conditions
data: `UserUpdate(${getQueryInfo()["id"]},'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','${formatParamString(oldpassword)}','${formatParamString(password)}','${formatParamString(picture)}','${formatParamString(role)}')`,
success: function(data, textStatus, xhr) {
// showing response from API
// showing response box that is added
//console.log(data)
$('#response').html("<div class='alert alert-success'>" + "<b>Success!</b> The information have been updated <b>successfully</b>" + "</div>")
Swal.fire({
icon: 'success',
title: 'Update Successfully!',
html: 'The information have been updated successfully!<br>By pressing <b>okay</b> this page will go to <b>view users</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: 'Okay',
cancelButtonColor: '#9b3be7', // purple
confirmButtonColor: '#79b446', // light green
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(function(inputvalue) {
if (inputvalue.isConfirmed) {
window.location.assign('viewUsers.html?id=' + getQueryInfo()['id'])
} else if (inputvalue.isCancel) {
Swal.fire('')
}
})
},
error: function(xhr, textStatus, err) {
if (xhr["status"] == 409) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> There is an <b>duplicate</b> on username!" + "</div>")
//then
// setTimeout(function(){ window.location.reload(); },5000); //reload a page after 5 seconds
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'There is an <label class="color-text"><b>duplicate</b></label> on username!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>username</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
if (xhr["status"] == 400) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> The <b>old password </b> is incorrect!" + "</div>")
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'The <label class="color-text"><b>old password</b></label> is incorrect!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>old password</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
// if (xhr["status"] == "(failed)") {
// $('#response').html("<div class='alert alert-danger'>"+"<b>Error!</b> There is an <b>duplicate</b> on username! where you cant add in image"+"</div>")
// }
}
});
})
I have a form which uploads images with progress bar. But selecting image is optional. It works fine when images are selected. upload.php gets both name and images. The problem is it can't send name or other form data while image is not selected.
the form-
<form id="uploadImage" action="upload.php" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label>File Upload</label>
<input type="file" name="uploadFile[]" id="uploadFile" accept=".jpg, .png" multiple/>
</div>
<div id="preview"></div>
<div class="form-group">
<input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div id="targetLayer" style="display:none;"></div>
</form>
<div id="loader-icon" style="display:none;"><img src="loader.gif" /></div>
Javascript code-
<script>
$(document).ready(function(){
$('#uploadImage').submit(function(event){
var x= document.getElementById("name").value;
if (x == '')
document.getElementById("preview").innerHTML= "name is required.";
else
{
if($('#uploadFile').val())
{
event.preventDefault();
$('#loader-icon').show();
$('#targetLayer').hide();
$(this).ajaxSubmit({
target: '#targetLayer',
beforeSubmit:function(){
$('.progress-bar').width('50%');
},
uploadProgress: function(event, position, total, percentageComplete)
{
$('.progress-bar').animate({
width: percentageComplete + '%'
}, {
duration: 1000
});
},
success:function(){
$('#loader-icon').hide();
$('#targetLayer').show();
},
resetForm: true
});
}
else
{
}
}
return false;
});
});
</script>
so while the image is not selected what to do in else part?
enter image description hereI was working on the php laravel framework. I need to prompt a sweet alert showing the terms and conditions on clicking the submit button. I have no clue to use sweet alert. I just used some of the templates and wrote the following code. It's not working. Can anyone help me with this
#extends('layouts.app')
#section('maincontent')
<div class="login-form">
<div class="container">
<div class="row ">
<div class="innerpage-box">
#include('layouts.errors')
<div class="innerpage-box-header text-center">
<h3></b>Products to Buy</h3>
</div>
<div class="register-box-body">
<!-- <p class="login-box-msg">REGISTRATION FORM</p> -->
<form role="form" id="myForm" action="/chemOrderSave" method="Post" class="bidDetailSave">
#csrf
<input type="hidden" name="product_id" value="{{$pro[0]->id}}">
<div class="row">
<div class="col-md-6">
<label> <b> Price: </b>
{{$pro[0]->price * 1.02}}
</label> </br>
<div class="form-group">
<label for="buyer_quantity"><b> Quantity </b> <star>*</star></label>
<input type="text" class="form-control" id="buyer_quantity" name="buyer_quantity" placeholder="Enter the Quantity" value="{{$pro[0]->quantity}}">
</div>
<div class="form-group">
<label for="chem_shipping">Shipping</label>
<select name="chem_shipping" class="form-control" required>
<option value="">Please select one of the following Shipping Addresses</option>
#foreach($us as $uss)
<option value="{{$uss->id}}" > {{$uss->address}} {{$uss->city}} {{$uss->state}} {{$uss->zipcode}} {{$uss->country}} </option>
#endforeach
</select>
</div>
</div>
<button type="submit" class="btn btn-success updateOrder" ><i class="fa fa-save"></i> Submit</button>
<i class="fa fa-close"></i> Cancel
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
In the custom.js I wrote the following code
$('.container').on('click', '.updateOrder', function() {
//e.preventDefault();
var id = $(this).attr('id');
var title = "Are you sure, By Clicking accept you agree to Farmerce's user agreement and are agreeing to follow through on this transaction !";
swal({
title: title,
type:'warning',
showConfirmButton: true,
showCancelButton: true,
allowOutsideClick: false,
confirmButtonText:'Confirm',
}).then((result) => {
if (result.value) {
$.ajax({
type: 'post',
url: '/chemBuyer',
data: {'_token': $('input[name=_token]').val(), 'id':id},
success: function(data) {
if(data == 'success'){
var title= 'Successfully Order Placed!!!';
var type='success';
}else{
var title= 'Some thing went wrong with the '+name+' !!!';
var type='error';
}
swal({
title: title,
type:type,
showConfirmButton: true,
confirmButtonText:'OK',
}).then(function(){
window.location.reload();
});
}
});
}
})
});
I'm trying send value by JSON. I enter value on HTML page but it doesn't work. It says "Name is null!";
<form action="" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="control-label" id="movieName" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="file" id="files" name="files" multiple />
</div>
</form>
<script>
$("#files").fileinput({
language: 'tr',
uploadAsync: true,
dropZoneTitle: "Please drop here pictures",
browseLabel: "Please choose picture",
uploadLabel: "Upload",
uploadUrl: "#Url.Action("Add","Movie")",
allowedFileExtensions: ['jpg', 'png', 'gif'],
maxFileCount: 4,
resizeImage: true,
maxImageWidth: 800,
maxImageHeight: 600,
resizePreference: 'width',
resizeImageQuality: 0.75,
uploadExtraData: { name: $("#movieName").val()}
});
</script>
If I enter standart value it works. Like this:
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="control-label" id="movieName" value="Test" />
<span asp-validation-for="Name" class="text-danger"></span>
but I want to send on HTML page I entered value. How can i do?
Your script is being executed as soon as the page loads, even before you have the chance to input something in the form fields. To solve this you need to only run your script when the form is submitted, like this:
<form action="" method="post" onsubmit="submitForm()">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="control-label" id="movieName" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="file" id="files" name="files" multiple />
</div>
<input type="submit">Submit</input>
</form>
<script>
function submitForm() {
$("#files").fileinput({
language: 'tr',
uploadAsync: true,
dropZoneTitle: "Please drop here pictures",
browseLabel: "Please choose picture",
uploadLabel: "Upload",
uploadUrl: "#Url.Action("Add","Movie")",
allowedFileExtensions: ['jpg', 'png', 'gif'],
maxFileCount: 4,
resizeImage: true,
maxImageWidth: 800,
maxImageHeight: 600,
resizePreference: 'width',
resizeImageQuality: 0.75,
uploadExtraData: { name: $("#movieName").val() }
});
return false;
}
</script>
A slightly more clear way would be to use addEventListener, like this:
<script>
function submitForm(event) {
event.preventDefault(); // Stop from reloading page etc.
// Rest of old script code
}
document.querySelector('form').addEventListener('submit', submitForm);
</script>
This lets you remove the onsubmit attribute in the HTML.
I want to validate a form in a bootstrap modal without using any framework. It's actually a simple modal with only an input text and two buttons "Close" and "Send".
The user should type his/her name in the input box and click send. The form is the sent with the method post.
What I want to do is that, if the user doesn't enter anything in the input box of and clicks on the button "Send", the input box should have a red border circling it instead of the default blue border. Here's the code for my modal:
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!--form-->
<form class = "form-horizontal" id="myForm" method="post" action="test.php" role="form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">My modal</h4>
</div>
<div class="modal-body">
<p>
Please enter your name:
</p>
<br/>
<div class="form-group">
<div class="col-lg-12">
<label class="control-label" for="firstname">Name</label>
<input type="text" class="form-control required" id="firstname" name="firstname">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="myFormSubmit" class="btn btn-primary">Send</button>
</div>
</form>
</div>
</div>
</div>
I tried using javascript to change the class of the input text to has-errorbut it doesn't produce the red outline. When I click on send it sends the empty value through the post method instead of
Here's my javascript code:
<script type="text/javascript">
$('#myForm').validate({
rules: {
name: {
minlength: 1,
required: true
},
},
highlight: function (element) {
$('#firstname').removeClass('has-success').addClass('has-error');
},
success: function (element) {
$('#firstname').removeClass('has-error').addClass('has-success');
}
});
</script>
I feel like I'm mixing a whole lot of things here. I'm still new to bootstrap and javascript. How can I go about getting the desired red outline?
Thanks.
Edit:
Validate function:
function validate() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
return false;
}
}
You need to change the CSS classes of the input parent element div.form-group, not the input itself:
The HTML after the submit button click should look like this:
<div class="form-group has-error">
<div class="col-lg-12">
<label class="control-label" for="firstname">Name</label>
<input type="text" class="form-control required" id="firstname" name="firstname">
</div>
</div>
To achieve this, alter your JavaScript code to this:
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
var firstName = $('#firstname');
// Check if there is an entered value
if(!firstName.val()) {
// Add errors highlight
firstName.closest('.form-group').removeClass('has-success').addClass('has-error');
// Stop submission of the form
e.preventDefault();
} else {
// Remove the errors highlight
firstName.closest('.form-group').removeClass('has-error').addClass('has-success');
}
});
</script>
div in boot strap...
<div class="form-group">
<div class="row">
<label class="col-xs-2 col-sm-2 control-label">city:</label>
<div class="col-xs-3 col-sm-3 formGroups"
id="city_form1">
<form:input name="city" class="form-control"
placeholder="City" data-toggle="tooltip"
data-placement="bottom" title="City" maxlength="15" />
<small class="help-block col-sm-offset-0 col-sm-9"
style="display: none;">city must require</small>
</div>
</div>
</div>
as you see there is .help-block is display: none now you write javascript function and check validation and if validation now pass make it display: block ... that's way you can do
enjoy with boot strap :)
its very easy
just apply class .has-error to div by javascript function
<div class="form-group has-error">
<div class="row">
<label class="col-xs-2 col-sm-2 control-label">city:</label>
<div class="col-xs-3 col-sm-3 formGroups"
id="city_form1">
<form:input name="city" class="form-control"
placeholder="City" data-toggle="tooltip"
data-placement="bottom" title="City" maxlength="15" />
</div>
</div>
</div>
Just use required inside the input field like this
<input type="text" class="form-control required" id="firstname" name="firstname" required/>