I'm new to Jquery and need a solution for a challenge.
What I need precisely is to store the inputs of a HTML form into an existing array. Do you know the Jquery logic to do this?
Here is a sample of the HTML that is the focus of this inquiry.
<form>
<input type="text" id="inputform" value""idkyet></input>
</form>
Example of how I'd like this to work:
User types name into form and clicks submit. That name is now stored into an existing array.
thank you.
Try
yourExistingArrayThatIsDefinedSomewhere.push($("#inputform").val())
console.log(yourExistingArrayThatIsDefinedSomewhere); //should show all previously pushed values
Note that you should add the code above to an event handler of the submit button.
<input type="text" id="inputform"> <input type="button" value="submit" id="submitform">
JS:
var your_array = [];
$("#submitform").click(function(){
your_array.push($("#inputform").push());
alert(your_array);
});
i think you should do a bit of studing yourself instead of just posting anything here.
Getting the value of the input in jQuery and adding it to an array would be something like this :
var array = [];
$("#inputform").change(function() {
array.push(this.value);
alert(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form>
<input type="text" id="inputform" value=""></input>
</form>
For example, here each time the value of the input changes, it will add it to the array.
Related
I would like to add another input field into the form each time I click the button in the code below. Using appendChild(), it seems as though I can only do this one time. I tried adding the field using innerHTML, but this removes what has already been typed in the existing form fields. What would be the best way to achieve this with vanilla JavaScript while keeping what has already been typed into the form? Thank you in advance for your help.
let getArticleForm = document.getElementById("articleForm");
let cloneInputNode = document.getElementById("textInput").cloneNode(true);
cloneInputNode.setAttribute("id", "newId");
function addInput() {
getArticleForm.appendChild(cloneInputNode);
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
Codepen
Clone it inside the listener, else you've only created one clone (which gets removed from its prior location when appended again).
let getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.getElementById("textInput").cloneNode(true));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
But there are some other fixes to make too:
The cloned nodes will all have the same ID, which is invalid HTML. While you could set a new ID for each input, dynamic IDs are an antipattern anyway - better to leave it off entirely IMO.
type="textarea" doesn't make sense as an attribute on an <input>. If you want a textarea, use a <textarea>.
Instead of cloning the existing input, consider just appending a new input.
const getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.createElement('input'));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
Below is my simple form html where I want to add the object data to my form fields. I went through Google search and StackOverflow but all of them were talking about jquery implementation, so here is my simple form html where I want to add the object data to my form fields. Since I'm not aware of Jquery, I want to use the Java Script approach.
Below, I have a user form where I want to bind the details object to my above form fields, so for that I'm using the below java script approach. I don't know where I'm going wrong. My object data is not getting bound with my form.
So kindly help me with it.
Thank you.
<!DOCTYPE html>
<html>
<body>
<div>
<form>
Name <input id="name" type="text" name="name"><br>
Place <input id="place" type="text" name="place"><br>
Age <input id="age" type="text" name="age">
</form>
</div>
<script>
var details ={name:'Krishna',place:'India',age:26};
document.getElementById("name").innerHTML=details.name;
document.getElementById("place").innerHTML=details.palce;
document.getElementById("age").innerHTML=details.age;
</script>
</body>
</html>
As mentioned in the comment by #Jaromanda X, there is no innerHTML for an input field. Instead, you should try setting the value attribute.
<script>
var details ={name:'Krishna',place:'India',age:26};
document.getElementById("name").value = details.name;
document.getElementById("place").value = details.place;
document.getElementById("age").value = details.age;
</script>
This should do the trick.
I've tried it a few different ways based on searches I've done on the subject and for some reason I can't get it to work. I just want my text inputs and textarea to clear after I hit the submit button.
Here's the code.
<div id="sidebar-info">
<form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
<h1>By Phone</h1>
<p id="by-phone">XXX-XXX-XXXX</p>
<h1>By Email</h1>
<p id="form-row">Name</p>
<input name="name" id="name" type="text" class="user-input" value="">
<p id="form-row">Email</p>
<input name="email" id="email" type="text" class="user-input" value="">
<p id="form-row">Message</p>
<textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
<p>*Please fill out every field</p>
<input type="submit" value="Submit" id="submit" onclick="submitForm()">
<script>
function submitForm() {
document.contact-form.submit();
document.contact-form.reset();
}
</script>
</form>
</div>
Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.
Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.
You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.
Try the following
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
since you are using jquery library, i would advise you utilize the reset() method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
You can use HTMLFormElement.prototype.reset according to MDN
document.getElementById("myForm").reset();
You can try this:
function submitForm() {
$('form[name="contact-form"]').submit();
$('input[type="text"], textarea').val('');
}
This script needs jquery to be added on the page.
The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with
$('#element-id').val('')
For all input elements in the form this may work (i've never tried it)
$('#form-id').children('input').val('')
Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.
There may be a better way however this should work for you.
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
btnSave.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
**Use the button you want to clear the inputs after clicking on it instead of the btnSave **
Just include this line at the end of function:
document.getElementById("btnsubmit").value = "";
I used the following with jQuery:
$("#submitForm").val("");
where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:
function extractValue() {
var value = $("#submitForm").val().trim();
console.log(value);
};
Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!
How do I access hidden fields in angular? I have an app, where I want to submit a form for each of items in the list. The form is simple - it has submit button and a hidden field holding the ID value. But it does not work. The value is empty.
I updated the default angular example to display the situation - the todo text is in hidden field.
http://jsfiddle.net/tomasfejfar/yFrze/
If you don't want to hardcode anything in your javascript file, you can either load it via AJAX, or do:
<input type="hidden" name="value" ng-init="model.value=1" value="1">
this way, you can keep the form functionality with JS off, and still use the hidden field in AngularJS
If you want to pass the ID from the ng-repeat to your code, you don't have to use a hidden field. Here's what I did:
For example, let's say I'm looping through a collection of movies, and when you click the "read more" link it will pass your ID to your JS code:
<ul>
<li ng-repeat="movie in movies">
{{movie.id}} {{movie.title}} read more
</li>
</ul>
Then in your JS code, you can get the ID like this:
$scope.movieDetails = function (movie) {
var movieID = movie.id;
}
In your simpler fiddle, the problem can be fixed by using ng-init or setting an initial value in the controller. The value attribute won't effect the ng-model.
http://jsfiddle.net/andytjoslin/DkMyP/2/
Also, your initial example (http://jsfiddle.net/tomasfejfar/yFrze/) works for me in its current state on Chrome 15/Windows 7.
You can do something like this.
It is a dirty trick, but it works (like most dirty tricks ;-)
You just use the form name as Your hidden field
and always give the form the id "form"
<!doctype html><html ng-app><head>
<script src="angular-1.0.1.min.js"></script>
<script>
function FormController($scope) {
$scope.processForm = function() {alert("processForm() called.");
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("form").name;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
};
}
</script></head><body>
<div ng-controller="FormController">
<form name="YourHiddenValueHere" id="form">
<input type="text" ng-model="formData.foo" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
</div></body></html>
This allows You to use ONE Controller for ALL forms and send
them to ONE server script.
The script than distinguishes by the
form name (formData.foo) and knows what to do.
The hidden field names the operation in this scenario.
Voila - You have a complete application with as
many forms You want and one server script
and one FormController for all of them.
Simpler:
<input type="hidden" name="livraisonID" value="{{livraison.id}}"/>
It works!
Use ng-binding="{{employee.data}}". It will work properly.
I have to correct (improve) myself:
You can do it more elegantly:
<form>
<input type="text" ng-model="formData.foo" />
<input type="hidden" id="bar" value="YourHiddenValue" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
and then in the JavaScript controller:
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("bar").value;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
So you can have as many hidden fields as you like.
I have a form in HTML with multiple inputs of type submit:
<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>
What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:
var name = $(this).find("input[type='submit']").val();
I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.
Try:
$(this).children("input[type='submit']:first").val();
how about the first selector
var name = $("input[type='submit']:first").val();