jQuery selector passes undefined for populated input field - jquery-selectors

This js script select the value of inputfield with name: id_add_to_cart and pass to ParseProductId that parse the value:
$("input[id='add-extra']").live("click",function () {
var product_id = $("input[name='id_add_to_cart']").value;
parseProductId(product_id);
return false;
});
The parsed value is undefined for this HTML:
<form action="" method="POST">';
<input type="hidden" name="id_add_to_cart" value="100" />
<input type="submit" id="add-extra" value="Add" />';
</form>
What am I missing?

$("input[id='add-extra']").live("click",function() {
var product_id = $("input[name='id_add_to_cart']").val();
alert(product_id);
});
change .value to .val().
Demo: http://jsbin.com/egiwor/2

var product_id = $("input[name='id_add_to_cart']").val();
Does this change anything?

Related

Why doesn't my React Js form accept user input?

I have a simple AddUser component and in the render function I am returning the following html:
<form ref="form" className="users-form" onSubmit={ this.handleAddNew }>
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={function() {}} /><br />
<input ref="email" type="email" name="email" placeholder="email"
value={this.state.email} onChange={function() {}} /><br />
<button type="submit"> Add User </button>
</form>
I am binding the state of username and email to this.state which I am setting to blank in getInitialState like so:
getInitialState() {
return { username: '', email: '' };
}
I am binding state to the form so I can set it to blank after form submission.
The problem with this setup is that the form now renders as readonly.
I cannot get any user input into either text fields. What am I doing wrong?
Your input fields are controlled components, since you are using the value property. This makes the inputs readonly and they will always reflect the value, the variable (in this case, the state variable) holds. You have to explicitly setState onChange since you are setting username field as a state variable.
Read more about it here
onUserNameChange : function(e){
this.setState({username : e.target.value})
},
render: function(){
return ...
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={this.onUserNameChange} /><br />
...
<button type="submit"> Add User </button>
</form>
}
A better way to do this is :
onChange : function(field,e){
this.setState({field: e.target.value});
},
render : function(){
return <form ref="form" className="users-form" onSubmit={ this.handleAddNew }>
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={this.onChange.bind(this,"username")} /><br />
<input ref="email" type="email" name="email" placeholder="email"
value={this.state.email} onChange={this.onChange.bind(this,"email")} /><br />
<button type="submit"> Add User </button>
</form>
}
It looks like you saw the console warning about controlled fields needing an onChange handler and added one just to shut the warning up :)
If you replace your empty onChange handler functions with onChange={this.handleChange} and add this method to your component, it should work:
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
(Or for people not using an ES6 transpiler:)
handleChange: function(e) {
var stateChange = {}
stateChange[e.target.name] = e.target.value
this.setState(stateChange)
}
However, if your component is an ES6 class extending React.Component (instead of using React.createClass()), you will also need to ensure the method is bound to the component instance properly, either in render()...
onChange={this.handleChange.bind(this)}
...or in the constructor:
constructor(props) {
super(props)
// ...
this.handleChange = this.handleChange.bind(this)
}

How to change URL form with GET method?

Form:
<form action="/test" method="GET">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
How to change URL form with GET method?
Before: test?cat3=1&cat3=5&cat3=8&cat3=18
After: test?cat3=1,5,8,18
I want to use jQuery.
Many thanks!
Here you go! This example, using jQuery, will grab your form elements as your question is asking and perform a GET request to the desired URL. You may notice the commas encoded as "%2C" - but those will be automatically decoded for you when you read the data on the server side.
$(document).ready(function(){
$('#myForm').submit(function() {
// Create our form object. You could optionally serialize our whole form here if there are additional parameters in the form you want
var params = {
"cat3":""
};
// Loop through the checked items named cat3 and add to our param string
$(this).children('input[name=cat3]:checked').each(function(i,obj){
if( i > 0 ) params.cat3 += ',';
params.cat3 += $(obj).val();
});
// "submit" our form by going to the properly formed GET url
var url = $(this).attr('action') + '?' + $.param( params );
// Sample alert you can remove
alert( "This form will now GET the URL: " + url );
// Perform the submission
window.location.href = url;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" id="myForm">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
My friend found a solution:
$(document).ready(function() {
// Change Url Form: &cat3=0&cat3=1&cat3=2 -> &cat3=0,1,2
var changeUrlForm = function(catName){
$('form').on('submit', function(){
var myForm = $(this);
var checkbox = myForm.find("input[type=checkbox][name="+ catName +"]");
var catValue = '';
checkbox.each(function(index, element) {
var name = element.name;
var value = element.value;
if (element.checked) {
if (catValue === '') {
catValue += value;
} else {
catValue += '‚' + value;
}
element.disabled = true;
}
});
if (catValue !== '') {
myForm.append('<input type="hidden" name="' + catName + '" value="' + catValue + '" />');
}
});
};
// Press 'Enter' key
$('.search-form .inputbox-search').keypress(function(e) {
if (e.which == 13) {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
}
});
// Click to submit button
$('.search-form .btn-submit').on('click', function() {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
$(".search-form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" class="search-form">
<input name="cat3" value="1" type="checkbox">1
<input name="cat3" value="3" type="checkbox">3
<input name="cat3" value="5" type="checkbox">5
<input name="cat3" value="7" type="checkbox">7
<br />
<input name="cat4" value="2" type="checkbox">2
<input name="cat4" value="4" type="checkbox">4
<input name="cat4" value="6" type="checkbox">6
<br />
<br />
Submit
<br />
<br />
<input type="text" placeholder="Search" class="inputbox-search" />
</form>

after submitting JSP form display result on same page

I am facing a problem in my Jsp page. I am filling the values in form and then clicking on Submit button. Now the problem which I am facing is, that I want the filled values to be shown in that division only in which I filled the form. I don’t want values/result of form to be displayed in next page.
My code of form is this:
<FORM id="Fid" METHOD="GET" ACTION="attributesWithModelInfo.jsp">
<INPUT NAME="make" TYPE="hidden" value="<%=(String) session.getAttribute("baseMake")%>"/><BR> <!-- This attribute is optional and can be used as a regular expression. -->
<INPUT NAME="model" TYPE="hidden" value="<%=(String) session.getAttribute("baseModel")%>"/><BR> <!-- This attribute is optional and can be used as a regular expression. -->
<INPUT NAME="year" TYPE="hidden" value="<%=(String) session.getAttribute("baseYear")%>"/><BR> <!-- This attribute is optional and can be used as a regular expression. -->
Attribute Name: <INPUT NAME="attribute" TYPE="TEXT" SIZE="30"/><BR>
Attribute Name: <INPUT NAME="attribute" TYPE="TEXT" SIZE="30"/><BR>
Attribute Name: <INPUT NAME="attribute" TYPE="TEXT" SIZE="30"/><BR>
Attribute Name: <INPUT NAME="attribute" TYPE="TEXT" SIZE="30"/><BR>
Attribute Name: <INPUT NAME="attribute" TYPE="TEXT" SIZE="30"/><BR>
<INPUT TYPE="SUBMIT">
</FORM>
Code of ajax that I am trying is:
$(function() {
alert('here I am in Attribute');
$("#Fid").submit(function(e) {
var name = $("#attribute").val();
var dataString = 'attribute='+ attribute;
$.ajax({
type: "POST",
url: "attributesWithModelInfo.jsp",
data: dataString,
success: function(){
}
});
e.preventDefault();
});
return false;
});
The form is in attributesWithModelInfo.jsp file.
This file is given its href in index.jsp as:
<li>Attributes</li>
The div in which Form is displayed and the result after submit too has to be displayed is:
$(document).ready(function() {
$('a#pageurls').on("click", function(){
$("#refdiv").load($(this).attr("href"));
return false;
});
});
the upper code too is in index.jsp

Disable submit button when form invalid with AngularJS

I have my form like this:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button disabled="{{ myForm.$invalid }}">Save</button>
</form>
As you may see, the button is disabled if the input is empty but it doesn't change back to enabled when it contains text. How can I make it work?
You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
To add to this answer. I just found out that it will also break down if you use a hyphen in your form name (Angular 1.3):
So this will not work:
<form name="my-form">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="my-form.$invalid">Save</button>
</form>
Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.
To void this, you just need to handle $pending state of the form:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>
If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>
We can create a simple directive and disable the button until all the mandatory fields are filled.
angular.module('sampleapp').directive('disableBtn',
function() {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var $el = $(element);
var submitBtn = $el.find('button[type="submit"]');
var _name = attrs.name;
scope.$watch(_name + '.$valid', function(val) {
if (val) {
submitBtn.removeAttr('disabled');
} else {
submitBtn.attr('disabled', 'disabled');
}
});
}
};
}
);
For More Info click here
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required/>
<button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>
</form>
If you want to be a bit more strict

Add a unique ID to form input for total

The problem I'm having is i'm working on an invoicing system. Which uses this,
$(document).ready(function() {
$('#add').click(function() {
JQuery('#lineItems').append('<input type="text" name="description[]"
class="ui-corner-all text invDesc" />
<input type="text" name="qty[]" class="ui-corner-all text invQty" />
<input type="text" name="amount[]" class="ui-corner-all text invAmount"
title="Amount" />
<input type="hidden" name="rowTotal[]" class="row-total-input" />');
});
});
to create new line item. The hidden input named rowTotal[] is meant to hold the totals of each row so they can be added up. The Code i am using to get the row total of qty * amount is,
$(function(){
$('.row-total-input').each(
function( intIndex ){
$('.invAmount').livequery('blur', function() {
var $this = $(this);
var amount = $this.val();
var qty = $this.parent().find('.invQty').val();
if ( (IsNumeric(amount)) && (amount != '') ) {
var rowTotal = qty * amount;
$this.css("background-color", "white").parent().find(".row-total-input").val(rowTotal);
} else {
$this.css("background-color", "#ffdcdc");
};
calcProdSubTotal();
calcOrderTotal();
});
}
);
});
However it updates all the rowTotal[] input fields to the last row total so the final sum isn't correct.
I am assuming I need to create some sort of unique ID for each rowTotal[] so only the correct one is updated. I just don't know how to do it.
Thanks in advance.
Ah the problem is here:
var qty = $this.parent().find('.invQty').val();
If each row would have a distinct parent it would be fine, but all the 'rows' are contained within the same parent - #lineItems. What should help is changing your current row creation code to this:
$(document).ready(function() {
$('#add').click(function() {
JQuery('#lineItems').append('<div><input type="text" name="description[]"
class="ui-corner-all text invDesc" />
<input type="text" name="qty[]" class="ui-corner-all text invQty" />
<input type="text" name="amount[]" class="ui-corner-all text invAmount"
title="Amount" />
<input type="hidden" name="rowTotal[]" class="row-total-input" /></div>');
//notice the extra div tag that wrapps around all the input fields
});
});