enhance name attribute in a form - javascript

I have a form, and add dynamically fields to it. After adding the fields I want to enhance the name attribute in the way that this:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="evening" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
</form>
Becomes:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-1-Workshops">
<input type="hidden" value="evening" name="form-1-Day">
<input type="hidden" value="3" name="form-2-Workshops">
<input type="hidden" value="morning" name="form-2-Day">
</form>
I have this to start with but I don't make any progress.....
var forms = $('form#workshops input[name$="Workshops"]');
for (var i=0, formCount=forms.length; i<formCount; i++){
$('form#workshops input[name$="Workshops"]').each(function() {
//$(this) seems to be empty
});
}

Try using this:
// Get all the forms inputs
var $forms = $('form#workshops input[name$="Workshops"]');
// Loop through each form inputs
$forms.each(function () {
console.log($(this));
});

Your code keeps re-selecting things inside of a loop. Makes no sense.
Use each to your advantage, it gives you the index so there is no need to do the for loop. .
function rename (i) {
var parts = this.name.split("-");
parts[1] = i;
this.name = parts.join("-");
}
var form = $("#workshops");
form.find('input[name$="Workshops"]').each(rename);
form.find('input[name$="Day"]').each(rename);

Maybe just try :
$('#workshops input[name$="Workshops"]').each(function() { /*...*/ });

Please try the following code:
var forms_input = $('form#workshops input[name *="Workshops"]');
forms_input.each(function() {
console.log($(this))
});

Related

Extract from JS to url

But I would be interested in how I can send this result from the js as a get
<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
<script type="text/javascript">
$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();
var total = 0;
$.each(values,function() {
total += parseFloat(this);
});
$("#test").text(total);
});
</script>
</form>
When I select inputs 1 and 2 so that the result is in url order2.php?price=20
$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();
var total = 0;
$.each(values,function() {
total += parseFloat(this);
});
$("#test").text(total);
$('form').attr('action', 'order2.php?price=' + total);
console.log ( $('form').attr('action') ) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
But I would be interested in how I can send this result from the js as a get
When I select inputs 1 and 2 so that the result is in url order2.php?price=20
<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
</form>
From your description that when you select option 1 and 2, you have the sum of the options as the price. I'll break this down into steps:
You have to sum the selected options
Construct your query param
Use Ajax to make your get request
This guides through how to do Ajax tutorial for post and get.
Hope this helps...
When a form submits, it will append all of it's inputs to the query string or post data (depending on the request type). A very simple way to add another field parameter called price with the sum is just to add a hidden input and update that dynamically with the sum.
Notice that I remove the name attribute from the checkboxes. I did this so that they wouldn't be send on the form submission.
I also replaced your forEach with a reduce() as it is more functional and you can chain it with the map()
$("#myform input").change(function() {
var total = $('input:checked').map(function () {
return $(this).attr('price');
}).get().reduce(function(sum, value) {
return sum + parseFloat(value);
}, 0);
$(".price").val(total);
$(".price").html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="order2.php">
<input type="checkbox" price="5" value="1" >5
<input type="checkbox" price="15" value="2">15
<input type="checkbox" price="20" value="3">20
<input type="hidden" name="price" class="price"/>
<input type="submit" value="send">
</form>
<span class="price"></span>

How to delay form submit?

I have a form that once the user clicks the Submit button - it runs 2 functions - (1) it pops up with a div that says 'Item added successfully to basket' then (2) a prefill function that sends the selected options to a Mals-E cart.
It works, but what i need to do is not let the form submit until the popup has shown for around 5 seconds - currently it flashes for a split second as the form is submitted immediately with the prefill function.
Can anyone help with this please?
Script Below:
function showDiv(f) {
document.getElementById('basket-center').style.display='block';
}
function prefill(f) {
var val = document.forms["basket"].elements["product[2]"].value;
val = val + gettext(document.forms["form"].elements['users']);
document.forms["basket"].elements["product[2]"].value = val;
document.forms["basket"].elements["price"].value = document.forms["form"].elements['sum'].value;
return false;
}
Form Script Here:
<form id="basket" name="basket" action="http://ww8.aitsafe.com/cf/add.cfm" method="post" onsubmit="showDiv(); prefill();">
<input name="userid" type="hidden" value="A1251773"/>
<input type="hidden" name="nocart"/>
<input name="product[]" type="hidden" value="{b}Sage 50 Accounts (The VAT Edition) 2014{/b}"/>
<input name="product[2]" type="hidden" value="{br}"/>
<input name="product[3]" type="hidden" value="{br}FREE Installation onto 1 Server/PC & Same Day Download when ordered before 3pm"/>
<input name="price" type="hidden" value=""/>
<input name="noqty" type="hidden" value="1"/>
<input name="thumb" type="hidden" value="sage50-thumb.png"/>
<input name="return" type="hidden" value="http://10.10.0.195/reality-solutions-development/sage-50-accounts.php"/>
<input type="image" src="img/buynow-button-green.jpg" border="0" alt="Buy Now" style="float:right; margin-top:-24px"/>
</form>
Try this:
//html
<form id="my_form">
<button id="my_button">submit</button>
</form>
//javascript
var my_form = document.getElementById("my_form"), button = document.getElementById("my_button");
my_form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
my_form.submit();
}, 5000);
return false;
}
Working jsfiddle: http://jsfiddle.net/njoqnwwf/
You could use Jquery for that
$(function() {
$('#form').delay(milliseconds).submit();
});

Radio buttons selected go to URL

I am trying to use the value of the selected radio button to go to a specific URL. Currently the Javascript I am using to do so is choosing the first "id" of the inputs and not using the value of what is actually selected.
HTML
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
Javascript
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>
You have multiple ID's that are the same, which is bad! getElementById expects one result, and it gets one by taking the first element which has that ID (ignoring your other 2, as it should). Use the class attribute on similar elements.
<input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student
And to get the checked element
var checkedElem = document.querySelector(".ns_license:checked");
And if querySelector is out of the question:
var elems = document.getElementsByClassName("ns_license"),
checkedIndex = 0;
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked)
checkedIndex = i;
}
Your current checked element would be at elems[checkedIndex]
to change a a specific attribute of an element, you can use the
setAttribute()
function of javascript. that should make it work.
While querySelector will work for modern browsers it does not work for IE <=7
If you want you can traverse through the radios by name, then check if the value is checked. If it is then return that value. That is the use of the getRadioValue() function:
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}
function getRadioValue(name){
var rads = document.getElementsByName('ns_license');
for(var x=0; x<rads.length;x++){
if(rads[x].checked){
return rads[x].value;
}
}
}
</script>

How to get the Specific Form Field value using JQuery

I have a form
<form id="post_comment" action="cmt.php" method="post">
<input type="hidden" name="type" value="sub" />
<textarea id="body"></textarea>
</form>
I am accessing the form using this code
$("#post_comment").submit(function(event){
var form = $(this);
});
How can I get the value of <input type="hidden" name="type" value="sub" /> from this form.
I tried to get using form.input("type") but it is not working.
$("#post_comment").submit(function(event){
var inputValue = $("input[name='type']",this).val();
});
Try using an id like this:
<form id="post_comment" action="cmt.php" method="post">
<input type="hidden" id='hidden' name="type" value="sub" />
<textarea id="body"></textarea>
</form>
and later:
$("#post_comment").submit(function(event){
var hiddenValue = $("#hidden").val();
});
<form id="post_comment" action="" method="post">
<input type="hidden" class="hidden" name="type" value="sub" />
<textarea id="body"></textarea>
<input type="submit" value="submit" class="submit"/>
</form>
$(".submit").click(function(){
var hiddenVal=jQuery("#post_comment .hidden").val();
//alert(hiddenVal);
});
var form = $(this);
var inputValue = form.find('input[name="type"]').val();
or
var form = $(this);
var inputValue = form.find('input:hidden').val();
Another approach for this
Consider if you have multiple forms with multiple input fields having name attribute than this code will be helpful for you :
$("#formId input[name='valueOfNameAttribute']").val()
$("#formId textarea[name='message']").val()
Hope it'll help somebody.
$("#post_comment").submit(function(event){
var form = $("input[name='type']").val();
})

jQuery Radio Button function not working properly

I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!

Categories