I can't do a submit with jquery - javascript

This is my page:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="/Scripts/jquery-2.1.3.js"></script>
<script>
function DoSubmit() {
if ($("#noAggLabel")) {
$("#noAggLabel").innerHTML = "";
}
if (this.value) {
$("#orderForm").submit();
}
}
</script>
</head>
<body>
<div>
<form action="/Orders/GetXML" id="orderForm" method="post"> <p>
<select id="OrdersSelect" name="productionOrderId" onchange="DoSubmit();"><option value="">Orders</option>
<option value="1">Order 1</option>
<option value="2">Order 2</option>
<option value="3">Order 3</option>
</select>
</p>
</form> </div>
<div id="codesTable">
</div>
</body>
</html>
I'm developing a ASP.NET MVC 5 app with .NET Framework 4.5.1 and C#.
This is the View that generates that HTML:
#model Models.ProductionOrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script>
function DoSubmit() {
if ($("#noAggLabel")) {
$("#noAggLabel").innerHTML = "";
}
if (this.value) {
$("#orderForm").submit();
}
}
</script>
</head>
<body>
<div>
#using (#Html.BeginForm("GetXML", "Orders", FormMethod.Post, new { id = "orderForm" }))
{
<p>
#Html.DropDownList("productionOrderId",
new SelectList(Model.ProductionOrders, "Id", "OrderNumber"),
"Orders",
new { id = "OrdersSelect", onchange = "DoSubmit();" })
</p>
}
</div>
#if (!Model.PagingInfo.HasAggregations)
{
<div id="noAggDiv">
#Html.Label("No tiene agregaciones", new { #id = "noAggLabel" })
</div>
}
<div id="codesTable">
</div>
</body>
</html>
Why I can't do a submit? I change selected value and nothing happens.

That's because the DoSubmit function isn't called with the element as the context. In the function this will refer to the window object.
You can set the context when you call the function:
onchange="DoSubmit.call(this);"
If you bind the event using jQuery instead of the onchange attribute, the context will be right:
$(function(){
$('#OrdersSelect').change(DoSubmit);
});
Side notes: There is no innerHTML method in jQuery, you would use the text or html method to set the content. You don't have to check if there is any element first, if there is no element, then the jQuery object will be empty, so calling text on it just does nothing.
You should check the content of the value. If you just use it in an if statement it will be converted to a boolean, so an empty string is still evaluated as true.
function DoSubmit() {
$("#noAggLabel").text("");
if (this.value != "") {
$("#orderForm").submit();
}
}

Remove the onchange attribute, and bind through jQuery
<script>
function DoSubmit() {
if ($("#noAggLabel").length) {
$("#noAggLabel").html();
}
if (this.value) {
$("#orderForm").submit();
}
}
$(function(){
$('#OrdersSelect').on('change', DoSubmit);
});
</script>
Also add .length to the $("#noAggLabel") test because it always returns a jQuery object (and it always evaluates to true when used in a boolean test).

Related

How do I properly display form HTML input

My code isn't working as I intend it to, and I don't know how to fix it. So, whenever the person types 'hello' in the box, and then presses Submit, the paragraph hat says hi is supposed to display 'good job', but it's not.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<textarea id="thesearchh" style="resize: none;"></textarea>
<button onclick="submitSearch()">Submit</button>
<p id="searchResult">hi</p>
<script>
function submitSearch() {
if(document.getElementById('thesearchh').includes('hello') == true) {
document.getElementById('searchResult').innerHTML = 'good job';
}
}
</script>
</body>
</html>
you should check input value with document.getElementById(inputId).value not with includes method. includes method works in arrays and strings but not on DOM elements.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<textarea id="thesearchh" style="resize: none;"></textarea>
<button onclick="submitSearch()">Submit</button>
<p id="searchResult">hi</p>
<script>
function submitSearch() {
if(document.getElementById('thesearchh').value === "hello") {
document.getElementById('searchResult').innerHTML = 'good job';
}
}
</script>
</body>
</html>
Stop using inline attributes like: CSS style and JS on* handlers. CSS and JS should be in their respective tags or files.
Use Element.addEventListener() instead of the onclick attribute handler
Use InputElement.value to get an :input's (<textarea> in your case) value.
Use === to compare it with the desired "hello" string
PS: are you sure you need a <textarea> instead of <input type="text">?
Additionally you might want to use String.prototype.trim() to remove whitespaces from your user-input string before comparing. That's up to you.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#search {
resize: none;
}
</style>
</head>
<body>
<textarea id="thesearchh"></textarea>
<button type="button" id="thesubmitt">Submit</button>
<p id="searchResult">hi</p>
<script>
// DOM Utility functions:
const el = (sel, par) => (par??document).querySelector(sel);
// Task: Match value "hello":
const elSearch = el("#thesearchh");
const elSubmit = el("#thesubmitt");
const elResult = el("#searchResult");
const submitSearch = () => {
const userInput = elSearch.value;
if (userInput === "hello") {
elResult.textContent = 'good job';
}
};
elSubmit.addEventListener("click", submitSearch);
</script>
</body>
</html>
Just added .value in your code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<textarea id="thesearchh" style="resize: none;"></textarea>
<button onclick="submitSearch()">Submit</button>
<p id="searchResult">hi</p>
<script>
function submitSearch() {
if(document.getElementById('thesearchh').value.includes('hello') == true) {
document.getElementById('searchResult').innerHTML = 'good job';
}
}
</script>
</body>
</html>
here you can see the line iam added .value
if(document.getElementById('thesearchh').value.includes('hello') == true){}

Javascript Function Not Preventing Form Submission with IF ELSE statement

I am using a small page to create a team of two members and it should stop the page from submission if someone selects the same member in both fields. I amusing following code:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create"
onClick="return checkDouble();" />
</form></html>
<script>
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble(){
if (2>1)
{
alert (tm2);
return false;
}
</script>
I have created a jsfiddle
If anyone can help it will be really helpful.
I know that my function is working as far as the calling the function is concerned but however somehow it does not work with if and else statement.
Try this . And Match the mmbr1 and mmbr2 selected value . And your function not closing properly with end of }
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble() {
if (mmbr1.value == mmbr2.value) {
alert(tm2);
console.log('fail')
return false;
}
else{
console.log('pass')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form action="" method="post">
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood2</option>
<option>Ahsan2</option>
<option>Usman2</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id" onclick="getText()">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>
</html>
<script>
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].text;
function getText() {
tm2 = mmbr2.options[mmbr2.selectedIndex].value;
};
console.log('选择的是' + tm2);
function checkDouble() {
if (2 > 1) {
alert(tm2);
return false;
}
}
</script>
enter code here
Forked yours, and added an event handler.
https://jsfiddle.net/springfeld/25ys4vm2/
First found: no closing bracket for your function.
One has to return a value, in every case, even if its dead code, so did i:
if (2>1)
return false;
return true;
Even if you strangle a function like checkDouble into onsubmit, as you did, you have to add an alternative. Think about like: What if 2 is smaller than 1? In that case the function now returns true, and evaluates correct in the eyes of your engine.
event.preventDefault();
within handler prevents it from running as designed, in your case to submit the form to the server. Think of it as a stop sign to the browsers default behaviour.
But keep in mind: This can be overridden by disabled javascript. If you disable javascript, forms values are submitted without further checks.
Hope: helps.
Have a nice.
Udo

How to select an ID in Jquery for an if statement

I want to use a form selector as shown, and depending on the option selected, a different output. Simple, yet I am not getting it to work. Here is what I have.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
if ("#1") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">1</td><td width="64">80</td><td width="93">32</td></tr></tbody></table>");
}
if ("#2") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">2</td><td width="64">88</td><td width="93">36</td></tr></tbody></table>");
}
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level">
<option id="1">1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
</html>
There were a couple issues here.
First of all, "#1" and "#2" are always going to == true, since they are strings.
Second, the code that changes the text only happens once, on page load. There is nothing telling it to update after the menu is changed.
Third, on the lines starting with $("#display").html...., you had what should have been a very long string, but you broke it up by using double quotes every time. You need to switch between single and double quotes. If I say, "class="potato">", it sees "class=" as one string, and ">" as another, but it doesn't know what to do with potato. You need to use single quotes, like "class='potato'>" or 'class="potato">'.
This is the fixed code:
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
function changeText(){
if ($("#level option:selected").text() == "1") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>1</td><td width='64'>80</td><td width='93'>32</td></tr></tbody></table>");
}
if ($("#level option:selected").text() == "2") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>2</td><td width='64'>88</td><td width='93'>36</td></tr></tbody></table>");
}
}
$(document).ready(function(){
changeText();
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level" onchange="changeText()">
<option id="1" >1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
Your javascript conditions are executed once, when the document is ready.
You have to add an event, when the select value change !
Add some values in your option elements ( <option value="1">1</option> )
$(document).ready(function(){
// Set event
$("#level").change(function(){
if ($(this).val() === "1") {
$("#display").html(...);
} else {
$("#display").html(...);
}
}
// Call event when document loaded
$("#level").change();
});

populate a HTML select in form using Javascript

I have a problem by populating a HTML select.
This select is in an form that first is loaded into a div. (see the code below)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function createForm(){
$("#formdiv").load("Register.html");
var itemval= '<option value="OT">OT</option>';
document.getElementById("sel").appendChild(itemval);
}
function validateForm(){
// ...
}
</script>
</head>
<body onload="createForm()">
<div id="formdiv" >
// here will be the form
</div>
</body>
The Register.html is a simple form
<h2>Register</h2>
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
The function createForm() should populate, here as a first test, the select tags. But unfortunately it does not show any option in the browser.
Hope some of you are more experienced than I and can hint me to the solution.
Thanks in advance!
Here the problem is that you use appendChild with a String,
you should use innerHTML to insert a string, or of you want to append
do createElement and then append, appendChild accepts Node as a parameter,
in your case its better use add() method on select
http://www.w3schools.com/jsref/met_select_add.asp
<script type="text/javascript">
function createForm() {
var option = document.createElement("option");
option.text = "OT";
option.value = "OT";
document.getElementById("sel").add(option);
}
function validateForm() {
// ...
}
</script>
<div id="formdiv">
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:
<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
</div>
<h2>Register</h2>
See jsfiffle link: http://jsfiddle.net/qgfbhgwd/
with a working example
You have 2 mistakes:
Use jQuery load function because is async so you are creating the content before loading the file register.html
appendChild needs a DOM Element instead of a string
This code fix your problem, hope it helps:
function createForm(){
var populateSelect = function() {
var itemsValues = ['OT', 'FOO', 'BAR'];
var items = document.createDocumentFragment();
itemsValues.forEach(function(el) {
var option = document.createElement("option");
option.value = el;
option.innerHTML = el;
items.appendChild(option);
});
document.getElementById("sel").appendChild(items);
};
$("#formdiv").load("register.html", populateSelect);
}
You can't add <option value="OT">OT</option> directly as appendChild, so use javascript createElement and always better to write a callback function for jquery load() to manipulate DOM.
function createForm() {
$("#formdiv").load("Register.html", function () {
//var itemval = '<option value="OT">OT</option>';
var itemval = document.createElement("option");
itemval.setAttribute("value", "OT");
itemval.innerText = "OT";
document.getElementById("sel").appendChild(itemval);
});
}

JavaScript assigned array values removed after invoking function

Using JavaScript to display a list of what was typed into the textarea element listed below. The values submitted are displayed for a split second, but are removed from the array right after the function is called. Would anyone care to explain why?
HTML
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<link rel='stylesheet' type='text/css' href='template.css'>
</head>
<body>
<header id='title'>
<h1></h1>
<h2></h2>
</header>
<div id='main_container'>
<div id='chat'>
<form id='messaging'>
<textarea id='current_msg'></textarea>
<input type='submit' value='send'>
</form>
<ul id='msg_list'>
</ul>
</div>
</div>
<script type='text/javascript' src='client.js'></script>
</body>
</html>
JavaScript
var msgList=[];
var form=document.getElementById('messaging');
var currentMsg=document.getElementById('current_msg');
var chat=document.getElementById('chat');
var ul=document.getElementById('msg_list');
function addText() {
if(currentMsg.value.length>0) {
if(msgList.length>=25) msgList.pop();
msgList.unshift(currentMsg.value);
currentMsg.value='';
console.log(msgList.length);
}
var concat='';
for(var index=0; index<msgList.length; index++) {
concat+='<li>'+msgList[index]+'</li>';
}
ul.innerHTML=concat;
}
if(document.addEventListener) {
form.addEventListener('submit', function() {
addText();
},
false);
}else {
form.attachEvent('onsubmit', function() {
addText();
},
false);
}
You need to understand the effects of having form:
1) User input some values
2) Once Submit the form get submitted , as you have not specified the action it will default to reload the current web page which means all inputs will be cleared
3) The html page get parsed from scratch , the JS code runs but it will only access the new values of inputs which are empty at this point
To make this work you need to remove the form tag

Categories

Resources