Onclick on normal button is submitting form - javascript

SCENARIO
I have a java JSP view with a long form. This was working nice. I can submit my form by pressing enter in any input field or with submit button.
NEW REQUIREMENT
In a part, I must add buttons to replace some <label> for <input> to allow editing, nothing hard.
WHAT I TRIED
This part of the view is created dinamically, cause number of lines depends of the data introduced by user, this parts creates each line:
resultadoHTML += " <div class='row col-lg-12 col-xs-12' style='margin-bottom: 30px;text-align: left;'>";
resultadoHTML += " <label class='col-lg-3 col-xs-12 control-label' >" + nomCalidad + "</label>";
resultadoHTML += " <div class='col-lg-5 col-xs-8'>";
resultadoHTML += " <input type='text' class='form-control' value='"+valor+"' id='calidadCatId' maxlength='30' required='true' />";
resultadoHTML += " </div>";
resultadoHTML += " <div class='col-lg-2 col-xs-3' id='ccc" + parts[1] + "'>";
resultadoHTML += " <label class='control-label' id='unidadCCC" + parts[1] + "' >" + parts[4] + "</label>";
resultadoHTML += " </div>";
resultadoHTML += " <div class='col-lg-2 col-xs-1'>";
resultadoHTML += " <button id='eCCC" + parts[1] + "' class='btn btn-default'><span class='glyphicon glyphicon-plus-sign'></span></button>";
resultadoHTML += " </div>";
resultadoHTML += " </div>";
Resulting HTML of the button
<button id="eCCC5" class="btn btn-default"><span class="glyphicon glyphicon-plus-sign"></span></button>
PROBLEM
When I use onclick to define a function in the new button, this function is called, but after, the click event of the submit button is ALSO called and I dont know why... But as you can see in the code, even when i DON'T catch any event in the button the click event of the form is called.
OTHER INFO
FORM/BUTTON DEFINITION
<form:form class="form-horizontal" role="form" method="post"
commandName="contratMercan" action="../contratos/contratosubmit"
name="formulario" id="edicionContrato">
<button type="submit" class="btn btn-primary" id="edicionContrato">
<spring:message ... /> // omitted info
</button>
SUBMIT FUNCTION
$("#edicionContrato").submit(function(e){
e.preventDefault();
var form = this;
// checks and workarounds...
form.submit();
});
Any idea why could happen? Maybe dinamically introduced HTML code has some mistake and brokes javascript or html after?

When you use the <button> element without specifying a type, it defaults to type="submit". You need to specify it as type="button" to stop it submitting the form:
<button type="button" id="eCCC5" class="btn btn-default">
<span class="glyphicon glyphicon-plus-sign"></span>
</button>

If you have button with attribute type="submit", clicking on submit will send whole form. I think if you add attribute type="button" or just delete it. Form probably won't send if you click on button or push ENTER being in input.

Another option is to place the button element outside the FORM would help but it depends on your requirements. If you need to put that button inside the FORM then you've to mention type="button"

Related

how to automatically add input field when a value entered and the cursor also focus newly created input field

i completed dynamically add row function but i want to, when a value exit the input field the button automatically add another row and the cursor also focus newly added row. i want to implement this functionalyty in my code for my php codignater project
my inputfield code
<div style="height:200px;width:1200px;border:2px solid #ccc;overflow:auto;">
<table id="rf_id">
<div class="form-group row col-sm-5" id="rf">
<tbody id="rf123">
<tr>
<td> </td>
<td> <input type="text" placeholder="Enter product RFID code"
id="rfid" class="form-control" name="rfid[]"></td>
<td> <i class="fa fa-trash-o delete_rfid"
style="font-size:25px;color:red"
onclick="removeOptionRow('0');"></i>
<i class="fa fa-plus-circle tr_rfid_add" id="tr_rfid_add"
style="font-size:25px;color:green" aria-hidden="true"
onclick="addFilterOptionRow();"></i>
</td>
</tr>
</tbody>
</div>
</table>
</div>
<div class="form-group row">
<div class="col-sm-4">
<input type="submit" id="assign_save" class="btn btn-success margin-bottom"
value="<?php echo $this->lang->line('save') ?>"
data-loading-text="Adding...">
</div>
</div>
My input field image
dynamically add row function for this input field, its a working function.
$("#rfid").focus();
function removeOptionRow(filter_row) {
$('#invrow' + filter_row).remove();
}
var filter_row = 1;
function addFilterOptionRow() {
html = '<tr id="invrow' + filter_row + '">';
html += '<td> </td>';
html +=
'<td><input type="text" placeholder="Enter product RFID code" id="rfid" class="form-control" id="option_name' +
filter_row + '" name="rfid[]" ></td>';
html += '<td> <i class="fa fa-trash-o delete_rfid" style="font-size:25px;color:red" onclick="removeOptionRow(' +
filter_row + ');"></i>';
html +=
' <i class="fa fa-plus-circle tr_rfid_add" onclick="addFilterOptionRow();" style="font-size:25px;color:green" aria-hidden="true"></i>';
html += '</td>';
//html+='</tr>';
//html+='<td>Remove</td>';
html += '</tr>';
$('#rf123').append(html);
filter_row++;
// $("#rfid").focus();
return false
}
expected:
i want to automatically add row when the value exit ,eg: i enter 'A' input to the input field ,the add button automatically add another input field.i try followying code but add button automatically click after defined time without entering input.
$(document).ready(function(){
$('#tr_rfid_add').click(function(){
});
if($('.#rfid').val()){
// set time out 5 sec
setTimeout(function(){
$('#tr_rfid_add').trigger('click');
}, 4000);
}
});
I hope someone will give a correct solution.
thank you

Prevent reload page with code added afterwards and after clicking a button

first of all I'm trying to create a form where is needed to duplicate some blocks of fields and fields as the user want.
So I have a page where there is a button that after clicking on it duplicates a certain block. The first button works fine!, it duplicates a block without reloading the page when is clicked.
But in that block there are some input fields that I need to duplicate as well.
So when the block is duplicated a new button is added to duplicate fields inside that block.
The problem is that when I click on the second button it reloads the page, instead of just duplicate an input field.
To do this I'm using jquery, code to duplicate the block, this is the code to add the block, that is working fine:
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
event.preventDefault();
});
code to duplicate the field (here is where the page reloads):
$('#we2_add_test').click(function(e) {
event.preventDefault();
$(".we2_test-input").append("<input type=\"text\" placeholder=\"Your Test\" class=\"form-control\" name=\"we3_test\" id=\"we3_test\">");
return false;
});
I already tried this, but it didn't work
1.id="we2_test" need to be class="we2_test" and id=we2_add_test need to be class="we2_add_test",because multiple same id for different HTML element is wrong when you are going to deal them with jQuery
2.Use event delegation:-
Now both code need to be:-
$('#add-block').click(function(e) {
e.preventDefault();
var html_to_add = '<input type="text" placeholder="Your Test we2_test" class="form-control" name="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test we2_add_test">+</button>';
$(".block-input").append(html_to_add);
});
$(document).on('click','.we2_add_test',function(e) {
e.preventDefault();
$(".we2_test-input").append("<input type='text' placeholder='Your Test' class='form-control we3_test' name='we3_test'>");
});
The first function has event as the function argument, but later on you try to use e.preventDefault(). That doesn't match.
Maybe
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.preventDefault();
});
will work? Difficult to say without the complete code though ...
Below is a somehow working version...
This is a little working snippet where I took care of the identity problem and the event delegation as mentioned/solved by #Alive to Die:
$(function(){
$('#add-block').click(function(e) {
var i=$('[name=we2_test]',".block-input").length;
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test'+i+'">'
+'<div class="we2_test-input col-md-12 no-pad"></div>'
+'<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.stopPropagation();
return false;
});
$('.block-input')
.on('click','#we2_add_test',function(e) {
e.preventDefault();
var j=$('[name=we3_test]',".we2_test-input").length;
$(this).prev().append('<input type="text" placeholder="Your Test" class="form-control" name="we3_test" id="we3_test'+j+'">');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
add block
<div class="block-input"></div>
Edit:
I replaced $(".we2_test-input").append(...) by $(this).prev().append(...) to ensure that only the div before the button gets added to.

How to hide, when page starts, html element generated automatically with jQuery

When page starts, jQuery produce a form that I want it to be hidden. Because I want to show it when I click on a button.
With these instructions I create the form:
$("#cards").append('<li id="card" class="feed-element animated fadeInRight" style="color: grey" data-user="' + key + '">\n\
<button id="previewCard" type="button" value = "' + key + '" class="btn btn-primary btn-sm btn-block btn-xs">' + preview + '</li>\n\
<form id="cardFormDetail" class="animated fadeInRight">\n\
<div class="form-group">\n\
<input id="customerCardDate" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<input id="customerCardScope" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<textarea id="customerCardText" class="form-control" rows="5"></textarea>\n\
</div>\n\
</form>\n\
<button id="modifiedCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-left">Modified</button>\n\
<button id="deleteRequestCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-right">Delete</button>\n\
<br><hr style="border-color: #c80b00;">');
When page starts cardFormDetail form is visible. How can I make it not visible?
I tried with $("#cardFormDetail").hide() but it doesn't work. And the reason is because it is a dynamic element, right?
Since you want to hide it on load, pls use CSS as opposed to jQuery unless there is a reason to justify why you want to do it so.
#cardFormDetail { display: none; }
put your code which hides the form after the code where it appends the element to the.
Another things is you are appending an element with the same id 'cards' to an existing element which has the same id.
It doesn't matter if your element is dynamically added, you should always be able to hide it using jquery.
Can you post the whole code?

Not able to propagate event listener (submit for form) for element generated by(later) javascript

I have html code like -
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>
The div 'insert_calendar_eda_form' is inserted initially.
Javascript code
calendar_eda_add_form = function (clicked_id, arraylength){
htmlstr = "";
htmlstr += '<a> Add Events for - </a>' ;
htmlstr += '<form id="calendar_eda_add_form" action="/setupaddcalendarevent" method="POST">'
htmlstr += '<label for="start_date">Start Date</label>'
htmlstr += '<input type="text" name="start_date" />'
htmlstr += '<label for="end_date">End Date</label>'
htmlstr += '<input type="text" name="end_date" />'
htmlstr += '<br> </br>'
htmlstr += '<input type="submit" value="Add Event" />'
htmlstr += '</form>'
$("#insert_calendar_eda_form").html(htmlstr);
The form 'calendar_eda_add_form' html is created dynamically by Javascript.
HTML code for event listener
<script type="text/javascript">
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', 'calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
Calendar_eda_add_form is generated dynamically by JS. I am trying to propagate the "submit" event, but does not seem to work. Can you please help?
Missing the hash tag on the selector inside the .on()
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', '#calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
Here's a fiddle showing it working http://jsfiddle.net/ja3kaa4b/ - are you seeing any console errors in the browser?
You may be experiencing the effects of duplicate IDs. In the function calendar_eda_add_form change the ID of the form to a class and use the following code instead:
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', '.calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
UPDATE
Per the comments under the question, the above is unlikely as the form is added to the DOM only once. However, the HTML being used is not valid:
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>
Per the HTML spec P elements can only contain inline elements; div - the target div - is not an inline element.
Why <p> tag can't contain <div> tag inside it?
http://www.w3.org/TR/html4/sgml/dtd.html
If I understand your question, this should work:
calendar_eda_add_form = function (clicked_id, arraylength){
htmlstr = "";
htmlstr += '<a> Add Events for - </a>' ;
htmlstr += '<form id="calendar_eda_add_form" action="/setupaddcalendarevent" method="POST">'
htmlstr += '<label for="start_date">Start Date</label>'
htmlstr += '<input type="text" name="start_date" />'
htmlstr += '<label for="end_date">End Date</label>'
htmlstr += '<input type="text" name="end_date" />'
htmlstr += '<br> </br>'
htmlstr += '<input type="submit" value="Add Event" />'
htmlstr += '</form>'
return htmlstr;
// in your code I dont see where you ever do anything with `htmlstr `.
// Since you made `calendar_eda_add_form` a function, I'm assuming you meant to return `htmlstr`
// and insert the created html into your `insert_calendar_eda_form` div
// im assuming you have a reason for `clicked_id, arraylength` here but not sure what they are for
}
$(document).ready(function(){
//change this line to add the `#` and bind to `document`
$(document).on('submit','#calendar_eda_add_form',function(event){
event.preventDefault();
somefunction();
});
//put here to simulate adding form later
$('#create').click(function(){
//insert the created html into your `insert_calendar_eda_form` div
$('#insert_calendar_eda_form').html(calendar_eda_add_form);
});
});
function somefunction(){
alert ('clicked add event');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="create" value="create form"/>
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>

jQuery click event is called wrong

I' ve this problem only with firefox. I' ve a function called by click event on a button tag but this is called also when I pick an option from my select tag. Anyone knows how handle?
jQuery
$("#search").click(function () {
var color = $("#selectedColor").html();
console.log("color to be sended -> " + color);
var input = $("<input type='hidden' id='color' name='color' value='" + color + "'/>" );
$("#form").append(input);
$("#form").submit();
});
Html
<label>Selected Area:
<span>
<p id="selectedPart">Area</p>
<p id="selectedColor">Color</p>
<button id="search">Search</button>
</br>
<form action="show" id="form" method="get"></form>
<select id="selectNii" form="form" multiple="yes"></select>
</span>
</label>

Categories