I'm new to JavaScript so need a help please. Basically I've two radio buttons and one submit button. I want to use JS function when submit button is clicked to pick the value of radio button.
<td align="right" style="width: auto">
#Html.RadioButton("SelectedOption", LinkOption.Link, true) Link Account
</td>
<td align="left" style="width: auto">
#Html.RadioButton("SelectedOption", LinkOption.DeLink, false) De-Link Account
</td>
<td align="right" style="width:50%">
<input type="submit" id="linkAccountSubmit" onclick="activeDeLink()" />
</td>
And the JavaScript function is; where I want to use the if statement to pick the value of radio buttons
function activeDeLink() {
if (............) {
$('.hiddenLink').each(function () {
$(this).removeClass('hiddenLink');
});
}
else
{.......}
}
you can get the value in this way:
$('input[name="SelectedOption"]').val();
Remember that your form will be submitted if you not return a boolean value from the function
<input type="submit" id="linkAccountSubmit" onclick="return activeDeLink()" />
function activeDeLink() {
if ($('input[name="SelectedOption"]').val() == "SomeValueToCheck") {
$('.hiddenLink').each(function () {
$(this).removeClass('hiddenLink');
});
return true;
}
else
{
// the condition is false, I dont want submit.
return false;
}
}
Related
I have following cshtml code in which "tr" is parent tag,"td" is subtag and checkbox and anchor tags are inside "td" tag.the submit button control code is mentioned on the topline . It's in the following ways. Also, jquery code is mentioned below what I am looking for is when I select the checkbox and don't fill any data inside the textbox and click on submit then a validation message should arise 'please fill the description' in some kind of colour. Currently, the situation is when select checkbox then disabled button changes state to enabled but text control inside anchor tag if left not filled with any data and click on submit it is not generating warning message also each checkbox has its own anchor tag like there are multiple checkboxes in a row and each checkbox has there own anchor tag.
<div class="col-xs-12">
<div class="submitbtn">
<button type="submit" id="submit
style="width:140px;height:30px;">Create 683</button>
</div>
</div>
#foreach (var item in Model.Items) /*-----to generate multiple rows-----*/
{
#if (#currentItem != item.Item)
{
<tr class="notifyAE-row text-center">
<td class="col-md-1">
<input type="checkbox" class="checks" id="chck" name="683radiobtn"
#*checked="checked"*# />
</td>
</tr>
}
<tr class="class_#item.Item">
<td class="col-md-2 ensuredoublespace text-left">
#if (canAddEditItemsReqMet.Succeeded)
{
<a href="#" class="explanations" data-pk="#item.Item" data-
type="text" data-
pendingItemId="#item.PendingItemId" data-name="#item.ValidItemBreakOutId" data-
compare683="#item.compare683" data-url="#Url.Action("UpdateExplanation", "Contract", new {
pendingItemId = item.PendingItemId, contractNo = Model.ContractNo, breakoutId =
item.ValidItemBreakOutId })">#Html.DisplayFor(model => item.Explanations)</a>
}
else
{
#Html.DisplayFor(model => item.Explanations)
}
</td>
</tr>
}
<script type="text/javascript">
$('#submit').prop("disabled", true);
$("input[type='checkbox']").click(function () {
if ($(this).is(':checked')) {
$('#submit').prop("disabled", false);
} else {
{
if ($('.checks').filter(':checked').length < 1) {
$('#submit').attr('disabled', true);
}
}
}
});
</script>
Below is my simple jsp form where i need to validate the whether the branch number is empty before doing the ajax call.
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" onsubmit="return validateForm()" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit" onclick="addData(); return false;"></input>
</td>
</form>
</table>
</div>
</body>
Below is my javascript
function validateForm(form) {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return false;
}
}
If i remove the return false; in the submit input it does populate alert form the branch input but it still calls the addData(). How to validate the form before call the function addData().
when you click on your submit button, your function addData will be called first and then your validateForm function. If I understood right, you want to validate the form on submission and then call your addData if everything is okay! In this case you can do this:
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form name="orderform" id="orderform" onsubmit="return validateForm();" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" >
</td>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div>
</body>
and the JS:
function validateForm() {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return;
} else {
addData();
}
}
function addData() {
// di stuff here with your data
alert('Everything is okay do stuff');
}
Make just one function that is called on submit event. Inside that function call another one like your validateForm(). If you discover that something is wrong while validating, call event.preventDefault()/event.returnValue = false or just return false as you already know. Also if you want branch numbers to be numeric, use isNumeric function instead of just checking if it is an empty string.
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isDataValid(data) {
// your checks...
if (!isNumeric(data.branch)) return false;
return true;
}
function addData() {
var e = event || window.event;
var data = {};
data.branch = document.forms["orderform"]["branch"].value;
// other data
// ...
if(!isDataValid(data)) {
console.log("Data is invalid! The submit will not happen!");
e.preventDefault();
} else {
// remove this else-branch later to make submit happen because the data in this case is valid
console.log("Data is valid! The submit will happen!");
e.preventDefault();
}
}
document.getElementById("orderform").addEventListener('submit', addData, false);
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit"></input>
</td>
</form>
</table>
</div>
PS don't forget to handle cross-browserness addEventListener/attachEvent, preventDefault/returnValue = false etc. Also you could collect errors inside isDataValid and show them later to users in case they inserted something incorrectly.
I have a button, when click, it do a jquery function and submit form too.
This is my HTML code:
<?php echo Form::open(array("class"=>"form-horizontal","method"=>"POST" ,"id"=>"frmMainOrders","enctype" => "multipart/form-data" )); ?>
<div class="search">
<tr class="tblAdvancedSearch">
<th scope="row">備考</th>
<td>
<input class="input_text_search" type="text" name="multi_column" id="multi_column_search" value=""/>
</td>
</tr>
<input type="submit" id="btn_submit" value="検 索" name="adv_search">
</div>
<?php echo Form::close();?>
This is my script jquery:
$('.search').on('click', function() {
showAdvancedForm(); // when click in div class=search, it do a jquery function name showAdvanceForm().
});
function showAdvancedForm() {
if($(".tblAdvancedSearch").css('display') == 'none') {
$(".tblAdvancedSearch").css('display', 'table-row');
} else {
$(".tblAdvancedSearch").css('display', 'none');
}
}
I have tried:
<input type="submit" id="btn_submit" value="検 索" name="adv_search" onclick="$('form').submit()">
This way allow me submit form, but my controller can not get attribute name="adv_search", so my function doesn't work.
I have tried preventDefault() and $('#btn_submit').click(false).
But both of them prevent all submit and jquery function.
Is there a way to submit the form but prevent ONLY jquery function when I click submit button?
You can use e.target.name to find out the name of the element. So based on that you can conditionally fire the method showAdvancedForm() .
e.target - Get the element that triggered a specific event
$('.search').on('click', function(e) {
if (e.target.name == "multi_column") {
console.log('calling method : showAdvancedForm');
showAdvancedForm(); // when click in div class=search, it do a jquery function name showAdvanceForm().
}
});
function showAdvancedForm() {
if ($(".tblAdvancedSearch").css('display') == 'none') {
$(".tblAdvancedSearch").css('display', 'table-row');
} else {
$(".tblAdvancedSearch").css('display', 'none');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" class="form-horizontal">
<div class="search">
<tr class="tblAdvancedSearch">
<th scope="row">備考</th>
<td>
<input class="input_text_search" type="text" name="multi_column" id="multi_column_search" value="" />
</td>
</tr>
<input type="submit" id="btn_submit" value="検 索" name="adv_search">
</div>
</form>
If you have a form and you want to send data via Ajax you should do something like this:
$('#formID').submit(function(e) {
e.preventDefault();
var submitButtonValue=$(this).children('input[type=submit]').val(); //This is 検 索
var data=$(this).serialize()+ "&adv_search="+submitButtonValue;
//probably your ajax call here...
})
Serialize is a function that you can get all your inputs' values in your form by it, and you also can easily send it via Ajax
You should use submit, because it also will check validations and more
I have a Javascript that triggers when the TrainingRequired checkbox is checked to show two submit buttons. When unchecked, one submit button is shown. The issue is when I check the checkbox and attempt to submit the form without data in one required field, an error message returns via postback. The checkbox remains checked and the two buttons no longer shows. How do I keep the two buttons visible after postback with an error message?
HTML markup:
<tr>
<td>
<label for="trainingRequired">
Training Required?*</label>
</td>
<td>
#Html.CheckBox("trainingRequired", Page.TrainingRequired, new { id = "chkImmediate" })
</td>
</tr>
<tr id="allowSelfTrainingBlock">
<td>
<label for="allowSelfTraining">
Allow Self Training?</label>
</td>
<td>
#Html.CheckBox("allowSelfTraining", Page.AllowSelfTraining)
</td>
</tr>
RegularButton and RequiredButton blocks:
<div id="RegularButton">
<input name="btn" type="submit" id="notrequired" value="Save" />
Cancel
</div>
<div id="RequiredButton">Create New Training Document?<br />
<input name="yesbtn" type ="submit" id="required" value="Yes" />
<input name="nobtn" type="submit" id="required2" value="No & Save" />
Cancel
</div>
Javascript on the same page:
<script type="text/javascript">
function prepareButtons() {
document.getElementById("RequiredButton").style.display = "none";
document.getElementById("RegularButton").style.display = "block";
}
//**********PostBack*************
function postBack(val) {
$('#xtravar').val(val);
$('form').submit();
}
$("#chkImmediate").change(function() {
if(this.checked) {
document.getElementById('allowSelfTrainingBlock').style.visibility = 'visible';
document.getElementById("RequiredButton").style.display = "block";
document.getElementById("RegularButton").style.display = "none";
}
else {
document.getElementById('allowSelfTrainingBlock').style.visibility = 'hidden';
document.getElementById("RequiredButton").style.display = "none";
document.getElementById("RegularButton").style.display = "block";
}
});
window.onload = function () {
prepareButtons();
}
After postback with an error message, I can get the two buttons showing if I uncheck and check the TrainingRequired checkbox. But I really want the two buttons to show after the postback with an error message. Thanks.
Since page would be redrawn after a postback, window.onload would be invoked again. Therefore, you would need to set a condition to check if an error occured. Since your using MVC, you may create a ViewBag prop in the controller and set it if an error occured. Something like the following.
In controller,
public ActionResult Validate()
{
if(Error)
ViewBag.isError = true;
return View();
}
In Js,
window.onload = function () {
var error = '# ViewBag.isError';
if(error != 'true')
prepareButtons();
}
I'm developing an extension that saves to storage, If the form has more than one button with the same id (not name so much, id is the identifier for chrome extensions), my check doesn't work.
<tr>
<td colspan="2">
<input type="Submit" value="Add" id="action" name="action" style="width: 100%" /></td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" value="Edit" id="action" name="action" style="width: 100%" /></td>
</tr>
Won't trigger my js (below), but this will
<tr>
<td colspan="2">
<input type="Submit" value="Add" id="action" name="action" style="width: 100%" /></td>
</tr>
JS
function manageItem() {
if (action.value=='Add') {
...
}
}
My intent was to use it like
function manageItem() {
if (action.value=='Add') {
...
} else if (action.value='Edit') {
...
}
}
If I only have one button with the id action, this works. If I have more than one button, this doesn't work at all.
For instance, when a browser submits to server side script, only the clicked submit button has its value sent, so this situation would work with that (just as an example).
I've tried testing each row in its own form, but I still get conflict when two elements have the same ID. What can I do?
Edit: I thought I had included in my question that I do know that id's cannot repeat, but I didn't explicitly say that. I know that in well-formed html, IDs cannot repeat, but I don't know how I can achieve this.
You should use class="action" instead of id="action", ids can't repeat.
Also, a typo: replace if (action.value='Edit') { with if (action.value=='Edit') {
In your current html, you don't really need neither ids or classes (but name is still needed) - you can remove these attributes, nor
function manageItem() {
if (action.value=='Add') {
...
} else if (action.value='Edit') {
...
}
}
To distinguish between your buttons, you can just use the following:
document.getElementsByName("action")[0].onclick=function(){
//first button clicked
}
document.getElementsByName("action")[1].onclick=function(){
//second button clicked
}