Submit div content contains form control states - javascript

I have a div with HTML tags and form controls like check boxes, text and drop lists. I want to post the whole content along with form controls' states (ie, capture user's choices) to save it into database and later, re-render the exact HTML.
How can I do that? I used
$("#div").clone()
But it seems control states not saved.
Note: I don't want to post the inner form, then re-render form states because the HTML is dynamic (it's a HTML template)

If I understand your question right, you need to store control states into HTML elements first (to a markup) and then submit div's innerHTML property...
See this fiddle - http://jsfiddle.net/esy1cc8z/
First of all you need to iterate over all form controls in specified DIV:
var ctrls = parent.querySelectorAll("input, select, textarea");
for(var i = 0; i < ctrls.length; i++){
var el = ctrls.item(i);
//...
And then store states of various form controls into DOM elements as attributes (= default values in HTML):
var type = el.getAttribute("type");
//For checkbox
//Checkbox
if(type == "checkbox"){
if(el.checked)
el.setAttribute("checked", "checked");
else
el.removeAttribute("checked");
//Other textual / numeric input types
} else {
el.setAttribute("value", el.value);
}
Of course if you need usable algorithm then you need to write conditions for all form control types, this is just an example...
Note: this is pure JS solution, using jQuery it may be simplier code...

Related

How to select for multiple fields with Jquery?

I currently have a form that is displaying fields that I do not want it to. There are 3 input fields associated with one form and the same form is being rendered multiple times.
I have my template set up to check for when this was only one value. I need to change it so the template will check for all of the values present & then decide to render.
So for example,
I have,
Div_id_form-0-x,
Div_id_form-0-y,
Div_id_form-0-z,
Div_id_form-0-location__location_category__requires_coordinates
What selector can I use to grab all of these to use in my template?
I need to grab them for each form. Where it says form-0 I have several of these forms repeating.
Then in HTML I have something like this.
$(function () {
// Determine weather we are in a modal window.
var context = $("#{{ contextId }}-form");
console.log("this is the {{ contextId }}" )
// Show required coordinates if location category requires them.
context.find("#id_location__location_category__requires_coordinates").change(function () {
if (context.find("#id_location__location_category__requires_coordinates").val() == 'Y') {
context.find('#id_needs_coordinates').removeClass('hide');
} else {
context.find('#id_needs_coordinates').addClass('hide');
}
});
});
Right now this is only checking for one value to determine whether to hide. I need it to check all of these for this value. Which is why I'm looking for a Jquery selector that can do such.
If you want a selector for IDs, you can use:
$("#Div_id_form-0-x, #Div_id_form-0-y, #Div_id_form-0-z, #Div_id_form-0-location__location_category__requires_coordinates")
Please see: https://api.jquery.com/id-selector/
Update
In the future, please clarify the entire issue and provide a proper example.
You can use the Attribute selectors.
$("[id^='Div_id_form-']")
This will select all IDs like:
Div_id_form-0-x
Div_id_form-1-x
Div_id_form-2-x
You will then select all of those elements.
See More: https://api.jquery.com/category/selectors/attribute-selectors/

The use of JavaScript onchange("<function>(this.id)") on c# CheckBox vs other c# Controls

I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.

How to navigate to last <input> tag in fieldset using Jquery in a Drupal View form

I am not a front-end developer and I have very limited exposure to JQuery JS etc. So any help is appreciated, thanks.
Objective : - I want to put the sum of all fields (except last ) of a fieldset into last field of that fieldset.
The form is rather complicated, in this form, there are multiple fieldsets and each fieldset contain multiple fields.
This form is generated by Drupal Views & I have very limited options to navigate in this form.
I can not use id, name or any other attribute as they are dynamically generated by CMS also there are hundreds of such fieldset so it is not feasible to write code for every one of them.
So, future addition of fields may alter the attributes. And I can not add my own attributes, classes, or ids to this form.
form looks something like this
<fieldset>
------<div>
---------<fieldset> **this one**
------------------<input>
------------------<input>
------------------<input>
------------------<input>
----------------nth <input> <= Sum of 1st to (n-1)th should come here
-----------------------<div>
I think that it can be done possibly through input:last but can't figure out how to use it properly.
Here is the function I wrote
$(function() {
$('input').change(function() {
var sum = 0;
// Loop through all inputs
$(this).closest('fieldset').find('input').each(function() {
sum += parseInt($(this).val());
console.log(sum);
// i want to put sum into last <input> tag of the current fieldset
});
});
}); // end function()
the output of console.log ($(this).closest('fieldset').find("input").last());); is
So, I figured that I have to extract attribute value, so far I have tried these
$(this).closest('fieldset').find("input").last().data('value'); Undefined
and
$(this).closest('fieldset').find("input").last().attr('value'); results in Undefined

Set multiple form values using jQuery Data attribute

So let us say i have a form with id #form which has two input fields, namely title & price.
I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
the obvious solution that works is
$("#name").val($(this).data('name'));
$("#price").val($(this).data('price'));
This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
Have tried this many ways with no success
Any help is appreciated
You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below
$.fn.applyData = function(form) {
$form = $(form);
$.each($(this).data(), function(i, key) {
$form.find('#' + i).val(key);
});
};
JSFiddle: http://jsfiddle.net/LCM8S/43/

Creating Clones of Forms using jQuery

using jQuery, how can you create a clone of a form without modifying the original form when a different value is selected in the clone. Currently, when selecting a value in the cloned form, the results that is returned is added to the results of the clone, as well as the original. I only want to results to appear for each unique form. Here is what i have:
<script>
$(document).ready(function() {
shows / hides results based on selection
$(".color-select").live("change" ,function(){
if($(this).val() == 'red'){
$('.red').removeClass('hide');
// toggles sub menus
$(this).parent('.controls').find('.submenu-select').removeClass('hide');
}
if($(this).val() == 'orange'){
$('.orange').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
if($(this).val() == 'yellow'){
$('.yellow').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
if($(this).val() == 'green'){
$('.green').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
});
;
// Duplicates category select menu
$(".add-color").click(function(){
$(".color-category").clone().removeClass('color-category').appendTo("#we-want-to").find('.submenu-select').addClass('hide');
});
$(".add-color-alternate").click(function(){
$(".color-category-alternate").clone().removeClass('color-category-alternate').appendTo("#we-want-to").find('.submenu-select, .results-table').addClass('hide');
});
Heres a fiddle with some html http://jsfiddle.net/mckenney42south/Z4yFs/
Thanks!
The reason you're seeing dickiness between your form's original and cloned instances are twofold:
A form relies on the name attribute for correct submission. In some circumstances, submitting a form with duplicate-named fields will result in an array being sent to the server; in other cases it will overwrite.
Without seeing the rest of your form - the fiddle isn't particularly helpful, sorry - it looks to me like your jQuery selectors are likely returning elements from the clone as well. To combat this, you might give each instance of the form a unique ID and chain your form-altering logic from its own $('#form-n') object, where "n" is to be replaced with the sequential ID number of your form.

Categories