simple javascript validation in asp.net mvc - javascript

I have very very stupid bug in javascript validation
let me i explain in code :
this is my form tag
<form method="post" enctype="multipart/form-data" name="myForm" onsubmit="return validateForm()">
<textarea id="content" name="Body"><%= Model.Body %></textarea>
</form>
and this is my script :
function validateForm(e) {
debugger;
var reviewMessage = $("[name='Body']").attr('value');
//var overallValue = document.getElementsByClassName('checkbox overall icon-checkbox').prop.checked;
if (reviewMessage.length < 100) {
e.preventDefault();
// $("Body").show();
$('#bodyValidation').css({'display' : 'block'});
return false;
}
return true;
}
my problem is that when ever i click the button page will be submited ;
but i want to stop this action with javascript .
how can i do that?

Your selector is wrong.
Change
var reviewMessage = $("Body").val();
to
var reviewMessage = $("[name='Body']").val();
OR
var reviewMessage = $('#content').val();

Related

How to Make addEventListener work on submit

am having problem making this to work on submit
it works well when using
document.getElementById("gets").addEventListener("click", b_button);
but not workng when i use
document.getElementById("gets").addEventListener("submit", b_button);
is there away to make it work on submit than using click
<form method="post">
<button type="submit" id="gets">Submit</button>
<p id="error"></p>
</form>
<script>
function b_button() {
document.getElementById("gets").disabled = true;
var time_meter = 10;
var runTimer = setInterval(function() {
if (time_meter <= 0) {
clearInterval(runTimer);
document.getElementById("error").innerHTML = "";
} else {
document.getElementById("error").innerHTML = 'counting ' + time_meter;
}
time_meter -= 1;
}, 1000);
setTimeout(function() {
document.getElementById("gets").disabled = false;
}, 10000);
}
document.getElementById("gets").addEventListener("submit", b_button);
</script>
you have to listen to form submit not to button submit
<form id="form" method="post">
document.getElementById("form").addEventListener("submit", function(e){ .... }
do not forget on e.preventDefault(); inside of your code to prevent unwanted submiting

Display textbox multiple times

The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>

Javascript form submits to new page -- how can I keep it on the same page?

beginner programmer here. Trying to create a very primitive "chat interface", in JSP where I type in some words, they're stored in an array, then, ideally, spit back out on the same page. I've got the code somewhat working, but it loads to a new page.
I've tried a number of different things that I read on the net, including trying to add "return false" to my showChats function, trying to change the submit to a button and doing "onclick", but it's still not working, always loads a new page. Any ideas on how to solve this?
Thanks in advance. Here's the code:
<script>
counter = 0;
//Array containing initial elements.
var chats = [];
function show_array(array) {
array[counter] = document.getElementById("chatlet").value;
for (x = 0; x < array.length; x++){
document.write(array[x] + "<br/>");
}
counter++;
}
</script>
<form action="agenda2.jsp" method="get" onsubmit="show_array(chats)" >
<p>
<textarea id="chatlet" rows="10" cols="30"></textarea>
</p>
<input type="submit" value="Send Chat">
</form>
</body>
</html>
You need to add return keyword with onsubmit like onsubmit="return show_array(chats)" and then return false in the JS function.
Code:
<form action="agenda2.jsp" method="get" onsubmit="return show_array(chats)" >
JS
counter = 0;
var chats = [];
function show_array(array) {
array[counter] = document.getElementById("chatlet").value;
for (x = 0; x < array.length; x++) {
document.write(array[x] + "<br/>");
}
counter++;
return false;
}
DEMO
Using query you could do below
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: 'get form data',
success: function (res) {
// handle response here
}
});
});
In the end of your function show_array() you have to add return false; Or in other case you might concider using jQuery and do this:
Give your form a class or id
<form class="myform">
....
</form>
<script>
$("myform").on('submit', function(e) {
e.preventDefault();
});
</script>
Regards!

Disable/Enable submit button and running this javascript every 1 second onload

I need to disable the submit button when the required fields are not filled. But the script is not working. If anybody can help, thanks in advance.
Html :
<input type="submit" value="Submit" name="sub1" id="submit1">
Javascript :
<script language="JavaScript">
function form_valid() {
var u1=document.getElementById("#user1").value;
var p1=document.getElementById("#pass1").value;
var p2=document.getElementById("#pass2").value;
var s1=document.getElementById("#school1").value;
if ((u1 == null)&&(p1 != p2)&&(s1 == null))
{
document.getElementById("#submit1").disabled = true;
document.getElementById("#submit1").setAttribute("disabled","disabled");
}
else
{
document.getElementById("#submit1").disabled = false;
document.getElementById("#submit1").removeAttribute("disabled");
}
}
function form_run() {
window.setInterval(function(){form_valid();}, 1000);
}
</script>
Body tag (HTML) :
<body bgcolor="#d6ebff" onload="form_run();">
var u1=document.getElementById("#user1").value;
Dont use #, you have many times in your code
var u1=document.getElementById("user1").value;

Return true - submitting an online form with Javascript

function FormSubmit(formid) {
this.initialize = function(formid) {
this.formid = formid;
$(formid).observe('submit', this.send);
}
this.send = function() {
alert('sending '+this.formid)
this.formid.onSubmit = true;
}
this.initialize(formid);
}
var form = new FormSubmit('donate_form');
<form method="post"
action="https://mysite.com/form_submit"
onsubmit="return false;" id="donate_form">
How can I make the above code, submit the form?
The event works, but the form doesn't submit.
Thanks
Rich
change
this.formid.onSubmit = true;
to
this.formid.submit();
Update
Whoops...forgot to double check the Javascript framework you were using. It looks like you're using Prototype. Please correct me if I'm wrong. In that case, instead of
this.formid.onSubmit = true;
you could try just
return true;
use document.forms[0].submit();
Also:
document.getElementById('donate_form').submit();

Categories