In my HTML, I have a normal form. The form takes inputs and submits. The user will then click a button called "#addOne". This button, using jQuery, appends a cloned form to the previous form. Each form is numbered, and each form is one less than its previous. The numbers will be used in my SQL WHERE clause. I want the cloned forms to be separate forms, For example, if I enter values for form 9 and click submit, and then enter values for form 8 the information won't collide with each other. Form 8's button should not submit for all the other forms.
Here's my jsFiddle: https://jsfiddle.net/2c2xL0cz/
HTML:
<div class="article_properties">
<form class="article_properties_form" action="" method="POST" enctype="multipart/form-data">
<p style="display: inline">Page Number</p><div style="background-color: #FF355E; padding: 5px; display: inline; margin-left: 5px"<p class="pageNumber"></p></div>
<textarea style="display: none" class="inputNumber" name="pageNumber"></textarea>
<p>Image</p>
<input type="file">
<p>Subtitle</p>
<input type="text" name="subtitle">
<p>Text</p>
<textarea name="text" rows="4"></textarea>
<input id="properties_btn" type="submit" value="Submit/Update">
<hr style="border: 1px dotted lightgray; margin-bottom: 50px">
</form>
<div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"><p style="text-align: center; line-height: 25px">+</p></div>
</div> <!--End of article properties div-->
jQuery/Ajax:
var numPages = 10;
$('.pageNumber').text(numPages);
$('.inputNumber').text(numPages);
$('#addOne').click(function()
{
numPages--;
var articlePropsTemplate = $('.article_properties_form:last').clone();
$('.article_properties_form').append(articlePropsTemplate);
$('.pageNumber:last').text(numPages);
$('.inputNumber:last').text(numPages);
});
$('.article_properties_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
}
});
});
Also, I do not wish to refresh the page when the form submits. For some reason, the dynamically created forms are creating page refresh when the submit button is clicked. There's also a solution in creating a div outside of the form elements, but this technique is making the forms think they're one form, but they should be separate forms all submitting to their respective pageNumbers.
Change this line
$('.article_properties_form').append(articlePropsTemplate);
To the below one
$('.article_properties').append(articlePropsTemplate);
Right now you are appending the new form with in the old form. So the data will get collide. You have to append the form outside the old form. So append the new form to the old form's parent
For prevent page reload of new forms
$('body').on('submit','.article_properties_form', function(e) {
//Your code
});
Or
$(document).on('submit','.article_properties_form', function(e) {
//Your code
});
Related
Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??
<form>
<p>
<input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
</p>
<p>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>
<p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, or javascript, you can easily control if a checkbox group has at least one checked element.
function myFunction() {
document.getElementById("myCheck").required = true;
}
<form action="/action_page.php">
Checkbox: <input type="checkbox" id="myCheck" name="test">
<input type="submit" onclick="myFunction()">
</form>
You can add logic to your clickHandler to check that the box is checked. So instead of calling getRandomImage() directly you add some logic to conditionally call the function.
function clickHandler() {
// get the checkbox element from the DOM
const checkboxElement = document.getElementById('vehicle3');
// see if the checkbox is checked
if (checkBoxElement && checkBoxElement.checked) {
getRandomImage();
} else {
console.log("The checkbox wasn't checked!");
}
}
// add the handler to the button
document.getElementById('generateButton').addEventListener('click', clickHandler);
I have to make a page, where there are 3 forms within it, but only one should be displayed. Also, these forms shouldn't be connected. For example if I would put in some kind of validation within all 3 of the forms, only the one I use should respond to the validation code, the other ones should stay idle untill I switch the form and use it. I have to make this without frameworks, plain, JS or PHP, HTML and CSS.
I have a page where I can switch forms, 1 is displayed, 2 are hidden. However, I made a validation class, and it is validating all 3 forms, since the 2 i'm not using are just hidden, not disabled so this is not working.
Any one know how I sould make these forms, so they would be independent from each other? I mean, how would they go about making this code, not making mine into account. I want to redo it and just add my other stuff on top of it.
if my deductions are correct on the little information given, here is probably what you are looking for
const
Bt_SwitchForm = document.getElementById("Switch-Form"),
FormX_Count = 3;
var
formActiv = 0,
formX = {};
function formX_Submit(e) {
e.preventDefault()
console.log('formX_Submit on =', this.id )
}
document.querySelectorAll('form').forEach( (elm, Item)=>
{
formX[elm.id] = { 'f' : elm, 'ref': Item }
elm.onsubmit = formX_Submit;
});
Bt_SwitchForm.onclick=()=>{
formActiv = ++formActiv % FormX_Count;
for(let elm in formX) {
formX[elm].f.className = formX[elm].ref===formActiv ? '': 'form_Off'
};
}
form {
display: block;
padding: 20px;
border: 1px solid grey;
width : 200px;
}
form.form_Off { display : none }
button { margin: 10px}
<form id="form1" class="">
<input type="text" id="inputTxt1" value="" placeholder="input form 1" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form2" class="form_Off">
<input type="text" id="inputTxt1" value="" placeholder="input form 2" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form3" class="form_Off">
<input type="text" id="inputTxt3" value="" placeholder="input form 3" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<button id="Switch-Form">Switch Form</button>
I think it is useless for me to explain this code since you seem to live with a strong power of deduction. ;)
I am just starting out with JQuery for asp.net core mvc.
I have a section of a page comprising a list of items linked to the main subject. When an 'edit' button is clicked against one of the list items, a hidden section (fieldset) is displayed and populated with the values of that list item. Other inputs on the page are disabled and the user can edit the item. All works fine.
However, when finished editing, the user clicks a 'submit' button (within the previously hidden fieldset) and the idea is to submit the edited data via ajax and, if accepted, to update the list. Ajax, etc. is not (yet) the problem.
When the user clicks the 'submit' button (coded as type="button"), the values in the edited section appear to have been cleared and are returned as spaces or nulls. It only seems to apply to this fieldset, as (disabled) values from the remainder of the document can be retrieved (just for testing purposes).
Can anyone tell me what is going on here and how to preserve these edited values, please?
#**** Drop-down section for editing Admissions ****#
<fieldset id="AdmissionsEditFieldset" class="app-edit-main-fieldset" hidden>
<legend id="AdmissionsEditLegend" class="app-edit-fieldset-legend">Editing Admission</legend>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
<div class="form-group">
<strong><label>Institution:</label></strong>
<span class="app-label-to-input-sep">
<input id="admId" name="aId" type="text" class="form-input app-can-disable" asp-for="Admission.Id" hidden />
<select id="admPlace" name="aPlace" type="text" class="app-can-disable" asp-items="Model.PlaceOfDetentionDd" asp-for="Admission.PlaceId"></select>
</span>
<strong><label class="app-input-fld-sep">Date Admitted:</label></strong>
<span class="app-label-to-input-sep">
<input id="admDate" name="aDate" type="text" class="form-input app-can-disable" asp-for="Admission.DateAdmitted" style="width: 5%" />
</span>
<strong><label class="app-input-fld-sep">Sequence:</label></strong>
<span class="app-label-to-input-sep app-can-disable">
<input id="admSeq" name="aSeq" type="text" class="form-input" asp-for="Admission.Seq" style="width: 5%" />
</span>
<span>
<button id="admSubmitBtn" class="btn btn-sm btn-primary app-adm-edit-btn" type="button">Submit</button>
<button id="admCancelBtn" type="button" class="btn btn-sm btn-danger app-button-to-button-sep">Cancel</button>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
</div>
</div>
And this is the JavaScript/JQuery
$(document).ready(function () {
$('.app-adm-edit-btn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// btn has format 'editN[N...]'
var btn = event.target.id;
var sid = btn.substring(4);
//*** Un-hide the editing drop-down
$('#AdmissionsEditFieldset').removeAttr('hidden');
//*** Copy values from the relevent line in the table to the editing drop-down
$('#admId').val($('#ident' + sid).text());
$('#admPlace').val($('#placeN' + sid).text());
$('#admDate').val($('#dateAdm' + sid).text());
$('#admSeq').val($('#seq' + sid).text());
//*** Set the section legend
$('#AdmissionsEditLegend').text('Editing an Admission');
//*** Disable other sections
DisableFieldsets(); // Works OK - makes no difference if commented out
//*** Focus the first input box
$('#admPlace').focus();
}); // $('.app-adm-edit-btn').click
/*----------------------------------------------------------------------------------
Admissions Submit button click handler
----------------------------------------------------------------------------------*/
$('#admSubmitBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// Just to verify nothing wrong with JSON.stringify
var id = $('#admId').val();
var placeId = $('#admPlace').val();
var seq = $('#admSeq').val();
var dateAdmitted = $('#admDate').val();
var court = $('#Court').val();
// Not integrated, so that I can display the values
var jsn = JSON.stringify({
Id: $('#admId').val(),
PlaceId: $('#admPlace').val(),
Seq: $('#admSeq').val(),
DateAdmitted: $('#admDate').val()
});
$.ajax({
url: "api/EditAdmissionApi",
method: "POST",
contentType: "application/json",
data: jsn,
success: function (data) {
alert("Ajax Success"); //TODO
}
});
alert(jsn);
//TODO
});
/*------------------------------------------------------------------------
Admissions Cancel button click handler
--------------------------------------------------------------------------*/
$('#admCancelBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
});
}); // $(document).ready
/*===========================================================================
Helper Functions
===========================================================================*/
/*---------------------------------------------------------------------------
DisableFieldsets Helper function to disable fieldsets while input of linked
items takes place
---------------------------------------------------------------------------*/
function DisableFieldsets() {
DoDisableFieldsets('#MainFieldset');
DoDisableFieldsets('#AdmissionsFieldset');
DoDisableFieldsets('#ChildrenFieldset');
DoDisableFieldsets('#SubmitButtonsNonFieldset');
}
function DoDisableFieldsets(id) {
var xId = $(id);
$('.app-can-disable', xId).attr('disabled', 'disabled');
$(xId).addClass('app-disabled-background');
}
Yes it does and many thanks for the suggestion, mj.
Trying to see why and testing alternatives brought me to the real issue, however. I have to confess that it was one of those stupidities that you can stare at for hours without seeing. Still I will confess, in case it helps anyone else.
I had given the Edit buttons in the list a 'dummy' class name to make selection easier. Then I had inadvertently copied and adapted the button html to be the Submit button following edit, without deleting the class. So both the Edit and Submit button handlers seemed to be called, which was causing havoc (I have not yet worked out why this was not just producing the unedited text in the second handler - but life's too short). So a dumb question on my part - sorry for wasting everyone's time.
The construct $('#admId').val($('#ident' + sid).text()); works fine now.
I have a form with a closure ui button:
<form id="login-form">
<div>
<input type="text" name="email" />
<input type="password" name="password" />
<div id="submit-login" class="goog-css3-button">Sign in</div>
</div>
</form>
I made my button submit my form:
var myButton = goog.ui.decorate(goog.dom.getElement("submit-login"));
myButton.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true);
goog.events.listen(myButton, goog.ui.Component.EventType.ACTION, function(e) {
goog.dom.getElement("login-form").submit();
});
Now, I have the 2 followings issues:
The form is not submitted when I push "Enter" in one of the fields
The event goog.events.EventType.SUBMIT is not triggered on the form,
so my eventual listeners wont be executed
How can I fix this?
The hack I found is to:
append an hidden button tag
trigger a click on the hidden button on the event ACTION
var hiddenSubmit = goog.dom.createDom("button",{ type : "submit", "style" : "visibility: hidden; position: absolute; z-index: -10000"});
goog.dom.appendChild(goog.dom.getElement("submit-login"), hiddenSubmit);
goog.events.listen(myButton, goog.ui.Component.EventType.ACTION, function(e) {
hiddenSubmit.click();
});
EDIT : As Safari and Chrome does not trigger events on hidden with "Display: none" elements, we must hide the button with other css rules
I am using jquery validation plugin. and designing the webpage using various elements (e.g,div ,li etc) .
There are tabs(tab1,tab2,tab3 ect) and through internal link these tabs contain several nos of fields(field1,,field2,....filed n).
Actually I want to mark the bg-color of the tab(e.g,tab2) as 'red' if there is any 'required' field missed .
For that I have tried the following code...
if(!(jQuery('#admissionForm').valid())) {
var n = $("label.error").parents("div.tab-body").index();
console.info(n);
var sel = "li.ui-state-default:nth-child(" + n + ")";
console.info(sel);
jQuery('label.error').each(function(n) {
$("label.error").parents("div#form-wizard").children("ul.ui-tabs-nav").children(sel).children("a").css("background-color","red");
});
}
The problems are
This code works for only one tab.
The .each() function takes the highest index.For example if there are error in all tabs then it marks only the 'tab3' tab not all the tabs.
So I want code which can mark the tabs. as respective error occurred as well doesn't mark the tabs which does contain any error.
Plz.. somebody help me out.
Thanx.. in advance...
This could be a little tricky to help you with. I'm not sure how familiar you are with the validate plugin.
You can't really do it the way you want it to, because you need to check all panels' inputs and see if they were valid or not.
The only way to differentiate that, without using the internal validation, is by using label.error:visible and label.error:hidden to see if they were valid or not. That is where your first problem lie. Since you have tabs, they are hidden even though they might be errored.
Which is why your example can only mark one tab or all tabs.
To solve this, you need to replace the current validation handler and unhighlight, so that you can do some highlighting and checking on your own.
I've arranged this JSFiddle that you can "fiddle" around with, hopefully the comments are enough to help you.
The idea is that at validation, you check which inputs were invalid, then get the parent panel and add an error class to the corresponding tab. When the user has corrected the error, or there is no error, the unhighlight will remove the error class from the tab.
And here's the code. Using JQuery, JQuery UI and JQuery validation plugin.
Javascript
$("#tabs").tabs();
$("#submitForm").button();
$("#validatetabs").validate({
submitHandler: function(form) {
alert("Done!");
},
invalidHandler: function(form, validator) {
//Check if there are any invalid fields
var errors = validator.numberOfInvalids();
if (errors) {
//Get all panels with errors
var errorpanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
//Get ui tab sibling for every panel and add error
errorpanels.each(function(){
$(this).siblings(".ui-tabs-nav").children("li").addClass("ui-state-error");
});
}
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass);
//Get panel
var panel = $(element).closest(".ui-tabs-panel", element.form);
if (panel.size() > 0) {
//Check to see if there are any more errors on this panel
if (panel.find("." + errorClass + ":visible").size() == 0) {
//Find matching tab for this elements panel id
panel.siblings(".ui-tabs-nav")
.find("a[href='#" + panel[0].id + "']")
.parent().removeClass("ui-state-error");
}
}
}
});
HTML
<form id="validatetabs" method="get" action="">
<div id="tabs">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
<div id="tabs-1">
A required field: <input id="inp1" name="inp1" class="required" type="text"/>
<br/>
Another required field: <input id="inp1a" name="inp1a" class="required" type="text"/>
</div>
<div id="tabs-2">
A required field: <input id="inp2" name="inp2" class="required" type="text"/>
<br/>
Another required field: <input id="inp2a" name="inp2a" class="required" type="text"/>
</div>
<div id="tabs-3">
A required field: <input id="inp3" name="inp3" class="required" type="text"/>
<br/>
Another required field: <input id="inp3a" name="inp3a" class="required" type="text"/>
</div>
</div>
<p>
<input id="submitForm" class="submit" type="submit" value="Submit"/>
</p>
</form>
CSS
label, input{
display: block;
width: 100px;
}
label.error{
position: absolute;
background: white;
width: auto;
margin-left: 125px;
margin-top: -26px;
padding: 2px;
color: red;
font-style: italic;
}