jQuery regex selector and get number from id - javascript

i have research form with few questions and answers and i'm trying to catch ID from id of form element (radio, checkbox, etc..). HTML form is generated dynamically from MySQL, that is a reason why id's and name's have only common value "question".
I have inputs like this:
<input type="text" name="question[1]" id="question-1" value="">
<input type="radio" name="question[2]" id="question-2" value="1"> Foo
<textarea name="question[3]" id="question-3"></textarea>
And i need to catch number from id. E.g. catch number 3 from id="question-3". It is possible to do that?
There is my js code. When you change value of any form element with id started "question-", data will be post. It works, but i need detect number in ID element, because i would like to generate next one ajax request (GET) to remove answer (e.g. /research/delete-answer/?id=3).
$('[id^=question-]').change(function() {
var formId = <?= $this->form->id; ?>;
var dataString = $('[id^=question-]').serializeArray();
$.ajax({
type: "POST",
url: "/research/save/?id=" + formId,
data: dataString,
success: function(data, status) {
console.log('Saved [' + status + ']');
console.log('Data [' + dataString + ']');
}
});
});
Thanks for help.

id="[^-]+-(\d+)
Try this.See demo.
http://regex101.com/r/pQ9bV3/4
var re = /id="[^-]+-(\d+)/g;
var str = '<input type="text" name="question[1]" id="question-1" value="">\n<input type="radio" name="question[2]" id="question-2" value="1"> Foo\n<textarea name="question[3]" id="question-3"></textarea>';
var subst = '';
var result = str.replace(re, subst);

$('[id^=question-]').change(function(event) {
var id = $(event.target).attr('id').replace('question-', '');
should give you the number within the id of the element which triggered the change event if that is what you were looking for, I am not totally sure what you are asking.

Related

How to get checked values of input tag which has array-name and send this values to server

I have a html-form:
<input name="arrayname[]" type="checkbox" value="1">
<input name="arrayname[]" type="checkbox" value="2">
<input name="arrayname[]" type="checkbox" value="3">
<input name="arrayname[]" type="checkbox" value="4">
Note the name attribute of input tag is set as arrayname[].
If I click some checkboxes and submit form then I get in $_POST global array:
["arrayname"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "3"
}
I want to get checked values from input tag using jQuery for sending them to server via ajax. I have invented javascript function:
function myGetValue(fieldName)
{
var value;
value = $('input[name='+fieldName+']').val();
return value;
}
But this function works with simple names without square brackets like 'simplename'. For example:
<input name="simplename" type="text" value="my text">
<input name="arrayname[]" type="checkbox" value="1">
<input name="arrayname[]" type="checkbox" value="2">
<input name="arrayname[]" type="checkbox" value="3">
<input name="arrayname[]" type="checkbox" value="4">
If I do alert(myGetValue('simplename')) then it is ok and I get the value of input field. If I do alert(myGetValue('arrayname')) then it is NOT ok and I get 'undefined'.
What function must be in use? I want to get value of input tag with name 'arrayname' and send it to server via ajax. I can't use serialization or json. I want to get the same array like the $_POST even using ajax.
You can see my code in live example here
I want send checked values only.
My code to send data via ajax:
var fieldName = 'simplename';
var fieldValue = myGetValue(fieldName);
var formaData = new FormData();
formaData.append(fieldName, fieldValue);
$.ajax({
type: 'POST',
data: formaData,
processData: false,
contentType: false,
});
You can use .map() to get the values of the checked checkbox elements as below - it will return an array
function myGetValue(fieldName) {
var value = $('input[name="' + fieldName + '"]:checked, input[name="' + fieldName + '"]:not(:checkbox, :radio)').map(function () {
return this.value
}).get();
return value;
}
Demo: Fiddle
You cannot define name as a Javascript Array object. It's a regular string.
Try this:
var checked_boxes = [];
$('input[name^=arrayname]:checked').each(function(){
checked_boxes[checked_boxes.length] = $(this).val();
});
alert(checked_boxes);
I don't see it, so what i'm guessing is that you are looking for following behaviour:
check your console
function myGetValues(fieldName) {
return $('input[name=' + fieldName.replace(/(\[)|(\])/g, function (m) {
return "\\" + m;
}) + ']').map(function(){return this.value}).get();
}
console.log(myGetValues('arrayname[]'));
Try this
function myGetValue(fieldName)
{
var value;
value = $('input[name="'+fieldName+'[]"]').val();
//or
//value = $('input[name="'+fieldName+'[]:checked"]').val();
return value;
}
alert(myGetValue('arrayname'));
you field name is arrayname[] so u have to give [] along with the name and also selector should be $('input["name="arrayname[]"]')
Live Demo
Updated
$(document).ready(function() {
function myGetValue(fieldName)
{
var values = [];
$('input[name="'+fieldName+'[]"]:checked').each(function(i) {
values[i] = $(this).val();
});
return values.join(",");
}
alert(myGetValue('arrayname'));
});
Live Demo

Getting multiple selected checkbox values in a string in javascript and PHP

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>

onclick checkbox append checkbox value to URL

I wanna implement this using jquery instead of inline but Its not working, inline works fine. The other reason I wanna use jquery is if user selects more than one checkbox, the url should be appended with whatever is already there + OR '2nd CheckBox Value' like this:
"http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office OR Hospital"
The space infront and following OR is fine..
How can I achieve this? Can someone help me out?
Offices<input name="LocType" type="checkbox"
value="Office" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office'; return true;">  
Hospitals<input name="LocType" type="checkbox"
value="Hospital" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Hospital'; return true;">  
Facilities<input name="LocType" type="checkbox"
value="Facility" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Facility'; return true;">
Bind to the change event on the checkboxes. When clicked read the current checkbox value and then all other relative checkboxes. Append your base url with your custom query string and go crazy. :)
This isn't tested but hopefully it's a good starting point.
var baseUrl = 'http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
You can try this.
HTML
<input name="LocType" type="checkbox" value="Office" />
<input name="LocType" type="checkbox" value="Hospital" />
<input name="LocType" type="checkbox" value="Facility" />
JS
Assuming you have a button or something on click of which you want to create a url with all the checked LocType checkbox values appended to the url seperated by OR
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('button').click(function(){
//This will get the array containing values of checked LocType checkboxes
var checkedLocTypeValues = $('input[name=LocType]:checked').map(function(){
return this.value;
});
//Use Array.join() method to join the array elements by " OR "
url = url + "&k=" + checkedLocTypeValues.join(" OR ");
//Now you can use url variable which has all the checked LocType checkboxes value
}
jQuery map() reference - http://api.jquery.com/jQuery.map/

Javascript: convert form to static

I'm working on an online application that uses a lot of forms like this:
<form action="..." id=".." method="post">
<label for="i0">something</label>
<input type="text" id="i0" .... />
<label for="i1">something</label>
<select id="i1"..> <option>a</option> <option>b</option> </select>
.....
<input type="submit" ...>
</form>
I use some JQuery plugins to serialize and deserialize data so I can save all data to database in one JQuery line and fill form with another instruction. My problem now is that in some context I need to show only the data, not editable form.
The question is: is there any JQuery plugin or some code that converts a <form> into a textual data preserving the form structure?
Note: a simple option is to show the form and disable all form fields, but this is not a good option if the user wants to print the data.
var html = '';
var $form = $('#form');
$form.find('label').each(function() {
var $label = $(this);
html += '<p>' + $label.text() + ': ' + $('#' + $label.attr('for')).val() + '</p>';
})
$form.replaceWith('<div>' + html + '</div>');
If you're doing that on submit, you could use jQuery form plugin and the formSerialize() function or beforeSubmit() callback.
var queryString = $('#myFormId').formSerialize();
or
$("#myFormId").ajaxForm({
beforeSubmit: function(arr, $form, options) {
// The array of form data takes the following form:
// [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
// return false to cancel submit
return true;
},
success: function() {
//success (your actions here)
}
});
(Use $form).
Here is non-jquery crossbrowser workaround:
var getOuterHtml = function(node){
var wrapper = document.createElement('div');
document.body.appendChild(wrapper);
var clone = node.cloneNode(true);
wrapper.appendChild(clone);
var result = wrapper.innerHTML;
document.body.removeChild(wrapper);
return result;
};
Here is working example.
P.S. By the way in ie you can use node.outerHTML.
EDIT: little bit modified example so that it wouldn't remove original form
I would propose a little different, but seems more appopriate solution - jQuery Templates
You keep you common code as template, depending on actual needs, you wrap those templates either to <forms> or <div>. This is more clear and easy to support.

jQuery hidden value not being sent

Is there a certain or special of dealing with hidden fields in jQuery? I am using a hidden input field and am not receiving a value. Obviously, my code is incorrect and would be grateful if someone could show me the error. many thanks
<input id="customer" name="customer" type="hidden" value="<?php echo $_SESSION['kt_idcode_usr']; ?>" />
$('#submit').click(function () {
var name = $('.uname').val();
var customer = $('.customer').val();
var department = $('#department').val();
var email = $('.email').val();
var position = $('.position').val();
var feedback = $('.feedbacknew').val();
var data = 'uname=' + name +
'&customer=' + customer +
'&department=' + department +
'&email=' + email +
'&position=' + position +
'&feedbacknew=' + feedback;
$.ajax({
type: "POST",
url: "feedback.php",
data: data,
success: function (data) {
$("#feedback").get(0).reset();
$('#message').html(data);
//$("#form").dialog('close');
$("#flex1").flexReload();
}
});
return false;
});
$('.customer').val(); ???
not ., #
result
$('#customer').val(); // works
try changing
var customer = $('.customer').val();
to
var customer = $('#customer').val();
you don't have such a class customer anywhere in this code
This line of code is wrong
var customer = $('.customer').val();
you have defined your hidden field by id, not by class, so you would need to use a # instead of a . on the selector
var customer = $('#customer').val();
The line you have here:
var customer = $('.customer').val();
...is looking for elements with a class called "customer". You don't have any such element. You have an element with an id of "customer". I suspect it will work if you simply change this line to:
var customer = $('#customer').val();
I'd suggest doing this for the rest of your input fields as well. Generally you'll want to identify them by id when collecting values to submit the form. Identifying them by class is typically more for things like styling different kinds of fields, binding event handlers, and so on.
note the difference:
alert($('.customer').val());
and
alert($('#customer').val());
. is for classes, see http://api.jquery.com/category/selectors/
I can see that for customer you are using jquery selector ".customer" which searches for an element with class name "customer" but your input has id equal to this, so:
var customer = $('#customer').val();
may I suggest serialize()?

Categories