I have a form in ASP.NET MVC which contains a DropDownList where I need to serialize the text value of the currently selected option in the list, not the value of that option. Then, I need to serialize a TextArea and send those both in the same query string. I have tried to select my DropDownList text using this JQuery statement:
var _dropDown = $('#ConfigList option:selected').text().serialize();
But I get the error:
Uncaught TypeError: $(...).text(...).serialize is not a function
My Question
How do I get the text value of my dropdownlist and my textarea, and serialize them together? They are both in the same input field which I am passing in to my JQuery function that serializes them.
// Bind a handler to update the hidden input when the select changes
$("select").on("change", function() {
$("#my_hidden").val(this[this.selectedIndex].text);
}).change();
// serialize it
$("button").on("click", function() {
var res = $("#my_textarea, #my_hidden").serializeArray();
$("pre").text(JSON.stringify(res, null, 2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="my_hidden" name=my_hidden type="hidden">
<select>
<option value="FOO_VALUE">foo
<option value="BAR_VALUE">bar
</select>
<br><textarea id="my_textarea" name=my_textarea>some content</textarea>
<br><button>serialize</button>
<pre></pre>
to serialize all form values you will have to use the ID of the form, it will automatically serialize all field values to serialized form. Also if you will use .text(), it will remove all html tags if any, so make sure before adding .text() to serilize.
Now for the dropdown if you really dont need the value tag anywhere den why are you putting that. remove it and then it will automatically get the text value which is visible in the dropdown.
var serialized = $("#form_name").serialize();
Related
How can I automatically fill a textarea field with the text from the database and automatically display the associated text when selecting an item from the dropdown menu.
Textarea field were I want to post the data in:
<textarea
class="dropDown" Name="dropdownItem" Type="Text" id="dropdownItem" placeholder="New Option"
></textarea>
Thats only a quick try that prints out the same input as the dropdownItem from my database.
<script>
var select = document.getElementById('select');
var input = document.getElementById('TextAreaTemplate');
select.onchange = function(){
input.value = select.value;
}
</script>
I already connect to the database, but I just don't know how to do this.
Do I need more JavaScript?
What you are doing here is only putting the value from your input to your textarea.
You need to make a query to your database with the value you get from your input.
I guess your connection is made via PHP (since you put the PHP tag), so I would recommend you to use AJAX request to create your query with the value from your input.
Then, your response should contain the associated text to display in the textarea.
I found this resource which show the basis of AJAX and PHP if you need, but you probably can find better.
Edit: Added a CodePenn to include a working example.
I'm taking a select choice from an HTML5 form and populating a Marketo Web form with its match.
Using some jQuery to get the value on the html element and match it with the marketo form . Once I choose the option on form A, it selects the option on form B
Form A = regular HTML5 form
Form B = Marketo web form
The Marketo form has extra fields that are not in the HTML until you select an option. Once you pick an option, it will inject other fields into the form. If I select the option value manually, it works fine, but when the script adds the value to the Marketo form, it does not fire/trigger the same way.
Regular HTML5 Form markup:
<form>
<div class="form-group">
<p><strong>I AM INTERESTED IN:</strong></p>
<select id="select-iminterestedin" name="contact_iminterestedin" class="form-control">
<option value="">Select...</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
</form>
Matching the option value on the second form:
// populate the select field
$('[name="contact_iminterestedin"]').on('change', function() {
const selected = $(this).val();
const matchValue = $(`#Initial_Product_Requested__c option[value="${ selected }"]`);
matchValue.prop('selected', true);
});
CodePenn demo of the entire thing:
https://codepen.io/bruno-gomes/pen/YbYBER?editors=0010
So once I select the field on the HTML5 form it adds the selected option to the Marketo form. However this does not trigger the additional field that would show up in the marketo form. But if I select the field on the marketo form manually, this new field shows up.
I would like to know/understand if the method im using specifically does not work how I would expect, or if there is a different approach maybe missing something related to .trigger('change') or .click('change')..
Unfortunately I'm unable to provide the HTML for the Marketo form. It gets loaded into the site via marketo API.
Any tips or help is very much appreciated!
Kind regards.
To fire that out you need to add one more line with the: document.querySelector('#target').dispatchEvent(new Event('change'));
NOTE: Triggering event as a jQuery .trigger('change') not working in that case.
Based on your code it will look like:
$('[name="contact_iminterestedin"]').on('change', function() {
const selected = $(this).val();
const matchValue = $(`#Initial_Product_Requested__c option[value="${ selected }"]`);
matchValue.prop('selected', true);
document.querySelector('#Initial_Product_Requested__c').dispatchEvent(new Event('change'));
});
Please note that it can be improved with the data attribute, since you have duplicates
in the code with the only change in #target selector.
Also using $(document).on('change', '#source', function(){...}); will help if the #source element will be added to the DOM after the event listener initialization.
$(document).on('change', '[name="contact_iminterestedin"]').on('change', function() {
const selected = $(this).val();
const matchValue = $(`#Initial_Product_Requested__c option[value="${ selected }"]`);
matchValue.prop('selected', true);
});
that code should be registering the even handler on the document
Use marketo's api to update the form. You will need the form's id to get the form and then from there you can use setValues when the html field is updated to set the marketo form's dropdown value. This will ensure everything works as expected.
$('[name="contact_iminterestedin"]').on('change', function() {
const selected = $(this).val();
const matchValue = $(`#Initial_Product_Requested__c option[value="${selected}"]`);
matchValue.prop('selected', true);
// get the form,
const form = MktoForms2.getForm(3578);
// set the form value you are interested in updating
form.setValues({
Initial_Product_Requested__c: selected,
});
});
Here's a codepen for you.
I am creating custom input field in html.Now i am facing problem how to submit data by using these custom fields. Custom field may be a radio option, may be it a select option, text field etc etc using can write name of that field by his own choice i want to know how to submit data of that fields in php and jquery.
<div id="custom fields">
//custom fields data
</div>
Is there any way to submit whole div fields with value ..If i write name in input text field and submit then my complete input filed and its value will save in database? when i retrieve these fields it will show input with value?
If you want to fetch multiple values than take a form else go for jQuery selector.
For multiple values (includes every types of DOM elements)
HTML :- <form id="formID"> ...... </form>
Access the form elements by using jQuery serialize function
NOTE :- serializeArray creates an array (not a "json array" -- there is no such thing); you can test this yourself with console.log($("#formID").serializeArray()). On the other hand, serialize creates a query string that's meant to be part of an HTTP request. Both representations are equivalent in the sense that using appropriate code you can convert one to the other without any ambiguity.
Example :- $("#formID").serialize(); OR $("#formID").serializeArray();
For single value
HTML :- <input id="name">
Javascript :- document.getElementById("name");
jQuery :- $("#name").val();
<div id="customfields">
//custom fields data
</div>
<script type="text/javascript">
setInterval(function () {
document.getElementById("customfields").value = document.getElementById("customfields").innerHTML;
}, 5);
</script>
You cannot submit fields in between div tag. Please use form tag to submit fields.
<form></form>
Are you find this?
$( "form" ).serialize()
I am using the jquery select2 plugin for suggestive form fields. I am trying to access the data stored in my original hidden input fields data attribute. I need the data from these attributes so I can send them to a php script via Ajax. Does anyone have any suggestions on how this would be done? I cannot seem to find a answer on google or the official website.
Thanks
You could also try the following. Suppose you have a select, you can add additional information to the options by using standard data-attribute syntax from jQuery, see jQuery data() API.
<select id="product">
<option value="prod_x" data-additional-info="1234X">Product X</option>
<option value="prod_y" data-additional-info="1234Y">Product Y</option>
</select>
Now in your javascript you can get to the option element itself by using .select2("data"), according to api docs - "Gets or sets the selection. Analogous to val method, but works with objects instead of ids". To get to the option object itself you have to go through the element, an array of all the selected options. In the example below the select is not multi value selectable so I always use the first object from the array, in addition to getting the object I wrap the result from ".element[0]" in $() to make it a jQuery object.
// Get the selected option using select2's api...
var selectedOption = $($("#product").select2("data").element[0]);
Now that we have a jQuery object we can use the jQuery data() API as follows to retrieve the arbitrary data stored on the option element.
var additionalInfo = selectedOption.data("additional-info");
The additional info variable will now contain either "1234X" or "1234Y" depending on which one was selected.
Using this you could eliminate the hidden inputs that holds the additional data and tie it directly to the selected option.
Like in the docs:
//Template:
<select>
<option value="0" data-foo="bar">option one</option>
</select>
//Initiate select2
$("select").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
//access custom data
function format(state) {
var originalOption = state.element;
return $(originalOption).data('foo');
}
We can get data attributes for the selected option
var seledted = $("#selectId").select2().find(":selected");
var s = $(seledted).data("data-field");
I ended up accomplishing this by
$(".suggestive-entry").click(function() {
var val = $(this).siblings('input:hidden').attr('data-field');
alert(val);
});
as you can see i used the siblings attribute to get the hidden input closest to the select2 box that generated the click event.
I am using this relatively simple JS program:
http://www.barelyfitz.com/webdesign/articles/filterlist/
The program just filters a select box using a text box.
However, I want to jquery and HTML5 data attribute which is different how it was originally used. I give my text box filterer a data attribute:
<input id="filter_text" name="filter_text" data-filterable="myselect"
type="text" />
I use the following jquery to get the name of the select box that is to be filtered and then filter the select box:
$(function() {
$('input[data-filterable]').keyup(function() {
select_box_name = $($(this).data('filterable'))[0];
filter = new filterlist(select_box_name);
filter.set(this.value);
});
});
which NEARLY works. You can filter but if you press backspace to de-filter then nothing happens i.e. it doesn't 'unfilter'.
It must be something really small!!
Thank you :).
You need to initialize the filter outside the event handler:
$(function() {
$("input['data-filterable']").each(function() {
var filter = new filterlist($($(this).data('filterable'))[0]);
$(this).keyup(function() {
filter.set(this.value);
);
});
});
On every keyup you're reinitializing filter. So you can only filter on the select as it is right when you press a key. Move the initialization of the filter out of the keyup event and it's working.
Here's a fiddle.