Not deleting data from Email select Box - javascript

I have working script which is sending emails from website to some array of emails.
Problem is: If the user forgot to choose value from select box (value = email to mail#mail.com in PHP array) my script is throwing alert "Choose a value!" but all data wrote by the user will be deleted from all select boxes.
Is there any way to avoid it?
JS:
function formSubmit() //onclick "Submit" button
{
var selectedValue = document.getElementById("sendTo").value;
if(selectedValue="99")
{
alert("Choose a value!");
}
else
{
//working ajax script which is sending emails
}
}
HTML:
<label class="company_emails">
<select id="sendTo">
<option value="99">Choose a department</option>
<option value="0">Justice</option>
<option value="1">Injustice</option>
<option value="2">Potatoes</option>
<option value="3">Mushrooms</option>
</select>
</label>

You have to stop the submit when there is an error, otherwise the form will be submitted and is empty again.
function formSubmit() {
var selectedValue = document.getElementById("sendTo").value;
if( selectedValue == "99" ) {
alert("Choose a value!");
// return false will stop the submit
return false;
}
}
But if you do it with onclick on a button you have to use return there too:
<button type="submit" onclick="return formSubmit();">send</button>
Or even better, if you have jQuery available, just register a listener on the form submit and use preventDefault. This is the best way imo.
$("form").on("submit", function(e) {
if( $("#sendTo").val() == "99" ) {
alert("Choose a value!");
// will stop the submit
e.preventDefault();
}
});
And as user #Carr said, you have missed a = in your if statement.

JavaScript code
<script type="text/javascript">
function formSubmit() //onclick "Submit" button
{
var selectedValue = document.getElementById("sendTo").value;
if(selectedValue="99")
{
alert("Choose a value!");
return false;
}
else
{
//working ajax script which is sending emails
}
}
</script>
And need to have return keyword on-click method of button as below.
<input type="submit" value="submit" onclick="return formSubmit()"/>

Related

How to validate JavaScript created element in asp.net core mvc

I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:

Need with Javascript function for Select check

I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.
I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?
Can you help me?
<script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a user");
return false
}
// add other checks here...
alert ("Thank you!")
window.open("Search.asp")
return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit" value="Submit">
</form>
Thank you very much!
It looks like something is wrong with the selector.
Comparing against a "0" value seems to work just fine. I've included a snippet which shows this.
In short, change this...
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
To this
if (document.querySelector("[name='UserID']").value == 0) {
alert("Please select a staff");
return false
}
Make multiple selections and submit to see the results.
function validateForm(daForm){
var select = document.querySelector("[name='UserID']")
if(select.value == 0){
console.log("Please select a value");
}else{
console.log("Selection made.");
}
return false;
}
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit">
</form>
You cannot just use UserID and work on it with JavaScript. That is the name of the select element. What you need to do is to select it using JavaScript and then work with it.
var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
// add other checks here...
alert ("Thank you!")
return true;
}
<== Fiddle Me ==>

Validating a form to not submit on empty input boxes

// html
<label>Write Data:</label>
</br>
<input type=text id=data name="data"style="width: 14em;">
</br>
</br>
<button id="write" type="submit" formaction="/output4" formmethod="post" style="width: 5em;">Write</button>
<button id="More" type="submit">Add more Parameters</button>
// js
$('#write').click(function(){
$('#data').each(function() {
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
return false;
}
});
});
I have a program where if a user clicks on a button, more write data boxes are appended. I do not want the form to submit unless all the write data boxes are filled out. The snippet above shows the alert box if an input if incomplete but then when you press ok, the form still submits?
You can use the .submit() event handler. Then use either return false or e.preventDefault() to stop the submit. Also note that id's are unique so $('#data') will only be a single element, so the .each() isn't needed:
$('#formIDHere').submit(function(e){
if ($('#data').val() == "" || $('#data').val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // or `return false`
}
});
For many inputs have your input items be a class with the value class="data". Just note you need to to use e.preventDefault() using the e from the submit event. In this case return false is for the .each() and not the submit. I use it here to stop the .each from going so we don't have many unneeded alerts and checks:
$('#myForm').submit(function(e){
$('.data').each(function(){
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // This is the preventDefault of submit
return false; // This stops the .each from continuing
}
});
});
Demo
$('#write').click(() => {
// if any one of the inputs is blank canSubmit will end up as false
// if all are not blank, it will end up as true
var canSubmit = [...document.querySelectorAll('input')]
.reduce((acc, input) => acc = input.value === '' ? false : acc , true)
});
<script type="text/javascript">
$(function () {
$("#data").bind("change keyup", function () {
if ($("#data").val() != "")
$(this).closest("form").find(":submit").removeAttr("disabled");
else
$(this).closest("form").find(":submit").attr("disabled", "disabled");
})
});
</script>
This would allow you to disable your submit button until there was data within the input field.

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

get the dropdown particular selected value and dispaly confirm box

I have member status select box in that i have open,read,close option is there.So when i'm selecting open or read and click update button it will updateing something.and i'm selecting close it display dialog box(Are you sure want close this)if yes it goes to some page or goes to no page.(I want to dispaly confirm box only particular value(22 only).
Anybody help on this one(js or jquery).It is smarty application
Here is my code
<html>
<head>
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val == '22') {
var state = confirm("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
</head>
<body>
<form method="post" action="/admin/member-modify-{$member->id}">
<label>Member state</label>
<select name="sel_state" class="validate" id="sel_state">
<option value=1>open</option>
<option value=2>read</option>
<option value=22>close</option>
</select>
<input name="submit" value="Validate" id="member_state_submit" type="submit" class="submit" Onclick="showClose();" />
</form>
</body>
</html>
All what you have to do is to wrap your JS code within {literal}{/literal} tags like this :
{literal}
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val=='22') {
var state = confirm ("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
{/literal}
In Smarty, anything within {literal}{/literal} tags is not interpreted, but displayed as-is. This will avoid interfering with the template delimiter syntax. Check the documentation.
This is simple with jquery
var value = $('#selector').text()
if (value == 22){
//do something here
}

Categories

Resources