I have a form with multiple blocks of inputs with default values assigned by PHP, and I would like to pass the HTML markup of one of the blocks into a PHP script. Here is a modified snippet of my form to exemplify the markup:
<form action="/page/do_work/job_number" id="work_form">
<textarea style="display: none;" name="markup" id="markup"></textarea>
<div id="block_1">
<table>
<tr>
<td><input type="text" value="123" /></td>
<td><input type="text" value="123" /></td>
</tr>
</table>
</div>
<div id="block_2">
<table>
<tr>
<td><input type="text" value="abc" /></td>
<td><input type="text" value="abc" /></td>
</tr>
</table>
</div>
</form>
I am listening for the submission of the form with some jQuery, so that I can copy the HTML of the table into the textarea.:
$('#work_form').submit(function(){
// Snatch the markup
var markup = $('#block_1', '#work_form').html();
// Place it into the textarea
$('#markup', '#work_form').html( markup );
// Move on
return true;
});
The Problem is that the modified values are not being copied into the textarea. For instance, if I were to change the values from "abc" to "xyz" the markup that is passed to the textarea still says "abc". Any help would be greatly appreciated.
Edit: Using .html() or .val() both add the markup in to the textarea, but I would like to know why the changes in value of the inputs are not reflected in the markup that is inserted into the textarea. Upon further inspection, changing the value of the input fields and then inspectigating them in Firebug shows the default value is retained. Do I need to update the DOM in some way?
Edit 2: The markup variable is being set, but the changes I make to the input fields are not reflected in the markup inserted into the textarea.
Try,
$('#markup', '#work_form').val( markup );
Also throw in a console.log(markup) to make sure the markup variable is getting set right.
Well for text area you need to change its 'value' not its 'innerhtml' and thats what .html does.
$('#markup').val(markup)
Try this.
Changes to input fields do not change the DOM, which is what I was supposed to do. To change the DOM, I edited the .submit() function to look like this:
$('#work_form').submit(function(){
// Update the DOM
var block_1 = $('#block_1', '#work_form');
block_1.find('input').each(function(i,e){
el = $(e);
el.attr('value', el.val());
});
// Snatch the markup
var markup = block_1.html();
// Place it into the textarea
$('#markup', '#work_form').html( markup );
// Move on
return true;
});
Thanks #PherricOxide for pointing me to this question:
reading innerHTML of HTML form with VALUE attribute (& its value) of INPUT tags
Related
I am trying to data bind a form element in knockout.js. However I don't want the element to be editable in the form, or even display the element to the user.
I'm able to correctly data-bind the value to an input element. But I would prefer if I could just pull the value from the HTML or a labels text, or a span. So the below works, but I'm not able to change it so it's not an input that the user can change.
<input id="txtProvider" name="txtProvider" type="text" data-bind="value: $root.session().Resource().provider" />
I tried just using a hidden element with a placeholder, but this didn't work.
<input id="txtProvider" name="txtProvider" type="hidden" placeholder="WebEx" data-bind="value: $root.session().Resource().provider" />
Any suggestions?
Thanks in advance for the help.
What you're doing works, or should work, fine:
<form>
<input type="hidden" data-bind="value: myHiddenVal" />
</form>
function ViewModel() {
self.myHiddenVal = ko.observable('Foo');
}
ko.applyBindings(new ViewModel());
This will yield:
<input type="hidden" data-bind="value: myHiddenVal" value="Foo">
Example: https://jsfiddle.net/thebluenile/myves32x/
Though I have to say, I of course don't know your exact use case, but "pulling values from HTML elements" is sort of antithetical to how Knockout, or any other data binding framework, works. If the user doesn't have to edit the field you can just keep it out of the UI altogether. The only valid use case for hidden elements I can think of would be if you were submitting the form to a server side script for processing, instead of sending its contents via AJAX.
I'm developing an app and I've a table populated with ng-repeat and the last column of the table is an image that it is clicked open another page that should contains more details about the line of the table that I've choose clicking the image.
I've tried to use an input type hidden in a form but it doesn't work for me.
This is my code:
<tr ng-repeat="Data in response">
<td align="center">{{Data.date}}</td>
<td align="center">{{Data.conf}}</td>
<td align="center">{{Data.evaso}}</td>
<form ng-submit="submit()">
<input type="hidden" name="codice" value="Data.code" ng-model="codice">
<td align="center"><input type="image" src="img/note.png" class="imageNote" ng-click="submit()"></td>
</form>
</tr>
After in the controller I need to manage this data (the cod). But in this way, I've tried to print it in the console and the result is undefined.
How can I solve this problem?
I am not sure if I get your question, but if you want to pass the selected item to the submit function, you can have your angular function like this:
$scope.submit = function(selectedId){
console.log(selectedId);
//Your code.
}
and your HTML should change to this:
<input ng-click="submit(Data.id)" type="image" src="img/note.png" class="imageNote">
Note: You do not need to use {{}} (expressions) to pass something to a function (here, ng-click)
I think you can try following way to get easily the Date.code data on click:
<input type="image" src="img/note.png" class="imageNote" ng-click="submit(Data.code)">
so I've been struggling with this issue.
I want to add a checkbox into a div dynamically by clicking a button. Let's say I already have 2 checkboxes in the div, then I uncheck those 2. When I click the button, the checkboxes become 3 (which is what I want), but all those 3 will be checked. What I want is when I add a checkbox, the other checkbox(s)' checked state remain the same as before.
Here is my code (http://jsfiddle.net/gr2o47wt/4/):
HTML:
<div id="chkbox_container">
<input type="checkbox" checked>Check<br />
</div>
<input type="button" value="Add CheckBox" onClick="addCheckBox();">
JavaScript:
function addCheckBox() {
txt = "<input type=\"checkbox\" checked>Check<br />";
document.getElementById('chkbox_container').innerHTML += txt;
}
Thanks in advance for your answers! :)
You can use insertAdjacentHTML() rather than manipulating the innerHTML:
<input type="button" value="Add CheckBox"
onClick="document.getElementById('chkbox_container').insertAdjacentHTML('beforeend','<input type=\'checkbox\' checked=\'checked\' />Check<br />');">
JS Fiddle demo.
The problem you had was that the original HTML (as returned by innerHTML) is from the source of the page, not the DOM; and therefore the checked/unchecked nature of the checkbox originally in place was restored.
insertAdjacentHTML() simply adds the HTML string in the specified place ('beforeend' in this case).
More or less as an aside, it's worth trying, where possible, to keep your event-handling outside of your HTML elements; and binding those event-handlers in the JavaScript itself. This makes for somewhat easier maintainability, and would lead to code like the following:
// note that I gave the button an 'id' for simplicity:
var button = document.getElementById('addCheckboxes');
button.addEventListener('click', function () {
document.getElementById('chkbox_container').insertAdjacentHTML('beforeend', '<input type=\'checkbox\' checked=\'checked\' />Check<br />');
});
JS Fiddle demo.
Finally, some of your HTML is invalid (or at least erroneous), an <input /> is a void element, it can have no descendants; therefore it either has no closing tag (just: <input>) or self-closes (<input />).
Further, the text beside the checkboxes is a little misleading, usually with an HTML form the text beside the <input /> will focus that input; that's achieved by using a <label> element to associate the text with the control, for example:
<label><input type="checkbox" /> click</label>
JS Fiddle demo.
Or:
<input type="checkbox" id="inputElementID" />
<label for="inputElementID">click</label>
But this latter form does require the dynamic generation of ids (which is a little beyond the scope of this question).
References:
insertAdjacentHTML().
I'm very new to using jQuery and JavaScript but here goes. I am trying to create a toggle function for my website. There is an input to select the name of the event which displays as default as a dropdown list of all the events in the database - but I want there to be an option to change it to manual input and type the name of the event as what ever you want.
I can get this to work fine! However I can't get the link to change the input BACK to a select box to work.
See my code below:
/// jQuery Code ///
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggleEventInput() {
$("#EventNameDropDown")
.replaceWith('<input type="text" size="35" name="boxEvent" class="FieldInput" />');
$("#EventNameChange")
.replaceWith(' (Drop Down Input)');
}
function toggleEventInputBack() {
$("#EventNameDropDown")
.replaceWith('TEST');
$("#EventNameChange")
.replaceWith(' (Manual Input)');
}
</script>
/// HTML Code ///
<table>
<tr>
<td class="label">Event:</td>
<td>
<span id="EventNameDropDown">
<select name="boxEvent" class="FieldInput" style="width:254px;" />
<?= $EventNameDropDownList ?>
</select>
</span>
<span id="EventNameChange">
(Manual Input)
</span>
</td>
</tr>
<tr>
<td class="label">Company:</td>
<td><input type="text" size="35" name="boxEvent" class="FieldInput" /></td>
</tr>
</table>
As said, when you click the original link to '(Manual Input)' it works fine and changes it to a text box. But then when you click the '(Drop Down Input)' link it does nothing.
Any help would be appreciated.
You need to use .html() instead of .replaceWith(). The former replaces the contents of the element. The latter replaces the element itself. By using .replaceWith() you are replacing the <span> that contains the <select> too.
Krishna is suggesting that rather than just replace the html for the <select>, you first store it in a variable so you can put it back later.
You could store it as data on an element, like this:
function toggleEventInput() {
// Store the html for the <select>.
$('#EventNameDropDown').data('selectHtml', $('#EventNameDropDown').html());
$("#EventNameDropDown").html('<input type="text" size="35" name="boxEvent" class="FieldInput" />');
$("#EventNameChange").html(' (Drop Down Input)');
}
function toggleEventInputBack() {
$("#EventNameDropDown").html($('#EventNameDropDown').data('selectHtml'));
$("#EventNameChange").html(' (Manual Input)');
// Clear the html for the <select>. We will get it again later if we need it.
$('#EventNameDropDown').data('selectHtml', '');
}
Its better to add the drop-down list inside a div/span and while clicking the toggle button, store the data inside the div/span to a variable and replace the content with the input box. on next toggle, replace the div/span with that data in the variable. a status variable 0/1 will help to toggle the data..
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.