Getting selected radio button in JavaScript - javascript

I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?

<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();

SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions

Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});

Related

Dynamically Create/Alter Form Fields from URL Parameters (Not Prepopulate Existing Fields)

In a formstack form, I need to be able to pass a list to the form as a parameter and, from that list, create checkboxes or dropdown menus that the user can select and that are saved in formstack's database and sent to integrations like all other fields. Here's an example of what I'd like to send in:
http://theformurl?list=option1,option2,option3,option4
From this, I'm trying to use code insertion in either (or a mixture of) the head, footer, or a code embed to create a new field on load that looks and acts like all the other fields.
I've been tinkering with Jenna Molby's approach to dynamically modifying html with url parameters found here:
https://jennamolby.com/tutorial-examples/dynamic-content-based-on-a-url-parameter-example/
But no luck so far. At present, I've not succeeded in getting dynamic text to populate in the form, let alone a form field that then talks to formstack's back end.
Is this doable, and if so, can anyone recommend an approach or a thread to pull on to figure it out?
--update
Thanks to Eric's suggestion, I was able to get halfway there. This code in the footer can commandeer a checkbox that you've already inserted in the form by id. It will replace that checkbox with the values you send in the url. But the selections don't get caught by Formstack when you submit.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put field number in var fieldNumber
var fieldNumber = "12345678";
//Put the parameter you're searching for in var param
var param = "parameter name";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "Prefix ";
//Put the question you want to ask here.
var theQuestion = "Which of the values that came through the url will you select?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "No variables were contained in the parameter.";
var theField = "field" + fieldNumber;
var theFieldID = "fsCell"+fieldNumber;
var values = url.searchParams.get(param).split(",");
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+ prefix + values[0] + "\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+(i+1)+"\" name=\""+theField+"[]\" value=\""+prefix+values[i]+"\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
}
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
</script>
Any thoughts on how to get it to talk to Formstack on submit?
Not familiar with formstack or what exactly you're getting from the URL and placing into forms or of what type, but I'll take a shot in the dark here.
Perhaps something like this:
var paramsToGet = ['param', 'param', 'param'];
document.addEventListener("DOMContentLoaded", function(event) {
let url = new URL(window.location.href);
paramsToGet.forEach((v)=>{
let thisParam = url.searchParams.get(param);
newFormElement(thisParam, x, x, "Default Value");
})
});
var newFormElement = (type, element_id, target_id, default_value) => {
default_value = default_value || null;
let el = document.createElement(type);
el.id = element_id;
if (default_value) {el.value = default_value;}
document.getElementById(target_id).appendChild(el);
}
So I've managed to find a solution that works for me. Thanks Eric for getting me started.
It requires adding two fields to the form you want to use this in: (1) a hidden text entry field where the selected values will be written, and (2) a placeholder checkbox field that this code will overwrite. You'll need to grab their id numbers, which I did by opening the live form and viewing source.
<script>
var selectedValues = [];
//This code goes in your Formstack theme footer. In the form that you want to add dynamic checkboxes to, create two fields using the WYSIWYG editor: a checkbox field and a text entry field. Make the text entry field hidden. You will need to know the id number of both the text entry and checkbox fields.
//Put the text entry field number in var textFieldNumber
var textFieldNumber = "field"+"12345678";
var index;
var checkboxFieldNumber = "12345679";
//Put the parameter you're searching for in var param
var param = "param";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "";
//Put the question you want to ask here.
var theQuestion = "Your question?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "Default message.";
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put checkbox field number in var checkboxFieldNumber
//Build the replacement HTML for the placeholder checkbox field.
var theField = "field" + checkboxFieldNumber;
var theFieldID = "fsCell"+checkboxFieldNumber;
var values = url.searchParams.get(param).split(",") || null;
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+values[0]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
//iterate through the array found in the url parameters, adding a new checkbox option for each element in the array.
if (values) {for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+"_"+(i+1)+"\" name=\""+theField+"[]\" value=\""+values[i]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
};}
//finalize replacement HTML
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
//write new HTML to DOM
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
function checkBoxToggle(thisBox) {
if(thisBox.checked) {
//When a new checkbox is selected, add its value to array selectedValues, sort it, and write it to the text entry field.
selectedValues.push(thisBox.value);
selectedValues.sort();
document.getElementById(textFieldNumber).value = selectedValues;
} else {
//When a checkbox is deselected, splice its value out of array selectedValues and write the array to the text entry field's value
index = selectedValues.indexOf(thisBox.value);
if (index > -1) {
selectedValues.splice(index, 1);
document.getElementById(textFieldNumber).value = selectedValues;
}
}
}
</script>

Js on change dropdown

I have a form that has a hidden text input that gets the user id called user_number_id and depending on the value the dropdown called departamento_drop gets an options filtered to retorno1. The problem is that when I open this form to edit something inside it, the selected option of this dropdown changes automatically and changes the real selected value. How can I keep the selected value selected and make sure the filter can understand that and have to respect it?
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var ret1 = '<option value="0">------ N/A ------</option>' + retorno1;
var ret2 = retorno1 + '<option value="0">------ N/A ------</option>';
if($("#departamento_drop option:selected").val() > '0'){
jQuery("#departamento_drop").html(ret2);
}else{
jQuery("#departamento_drop").html(ret1);
}
});
});
after 9 hours of work on it, I done this solution but still I need to find how to remove the selected option from retorno1 to not be duplicated, and for sure if there is any other idea better please share. thank you
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var i = 0;
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(retorno1)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
for(i=0; i < count; i++){
var val_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").val();
var text_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").text();
if (val_drop == dep_dr){
jQuery("#departamento_drop").html("<option value ='"+val_drop+"' selected='selected'>"+text_drop+"</option>"+pre);
}else if(dep_dr == '0'){
jQuery("#departamento_drop").html("<option value ='"+dep_dr+"' selected='selected'>------ N/A ------</option>"+pre);
}
}
});
});

Add live text from input field to another div with Checkbox

I have an input field with Add button below it. Also have another Div class named .new-option-content
What I am trying to do is if anyone type something in the input filed and click the +ADD button this text of the input filed will append with a Check box inside .new-option-content div.
Here is the Fiddle
I tried with this but I guess with this process I can't get the result.
$( ".checklist-new-item-text" )
.keyup(function() {
var value = $( this ).val();
$( ".new-option-content" ).text( value );
})
.keyup();
I am not good with advance jquery. I did tried to find something similar but failed. I am not sure if this can be done with jquery.
Any help or suggestion will be appreciated.
$("#add").click(function(){
var newLabel = $("#optionInput").val();
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
$(".new-option-content").append(newOption);
$("#optionInput").val(''); //clearing value
})
Fiddle: http://jsfiddle.net/has9L9Lh/8/
If you want to use it in multiple places on your page, you can try this modified version:
$(".new-option-add").click(function(){
var labelInput = $(this).parent().parent().find(".checklist-new-item-text")
var newLabel = labelInput.val()
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
// where to append?
var listToAppend = $(this).attr("data")
$("." + listToAppend).append(newOption);
labelInput.val(''); //clearing value
})
We are using data attribute value on the button, to assign class name of the list, which need to be updated.
Fiddle: http://jsfiddle.net/has9L9Lh/18/
Here is how you can do it:
$(function() {
$('.new-option-add').on('click',function() {
var noc = $('.new-option-content'),
val = $('.checklist-new-item-text');
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
And this should work for multiple sections:
$(function() {
$('.new-option-add').on('click',function() {
var section = $(this).closest('section'),
noc = $('.new-option-content', section),
val = $('.checklist-new-item-text', section);
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
Many have answered, yet another option is to use .clone(), cause otherwise you can end up in a maintainence nightmare, so something like
$(".new-option-add").click(function() {
var checkbox = $(".checkbox:first").clone(), value;
value = $(".checklist-new-item-text").val();
checkbox.html(checkbox.html().replace('Sample 1', value));
checkbox.appendTo($(".new-option-content"));
})
http://jsfiddle.net/has9L9Lh/19/
you can do this by adding this code
on click event
$('#yourDiv').append(' <label><input id="chkbox" type="checkbox"> "+$('#yourText').val() +" </label>');

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

how to make input fields editable?

I have this fiddle which is having user tab.In user tab ,there are three fields which accepts name,mobile and email.When a user fills all the three and hits add button then a row is inserted.Now i want to make the new added row editable.This means that I want to keep 2 bootstrap buttons edit and delete.So if delete is pressed then the entire row will be deleted and if edit is pressed then the entire will be editable where user can change the mobile number,name and email.Can any body please tell me how to do.
This js code adds new rows
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
This question is so specific to the OP scenario, so i will try to make the answer a bit more general.
I'm no expert here, but it seems you already capture the user's input and cloned it when they click Add to a new td. Therefore from what I understood is that you need to edit/delete the data from the new created td.
We have a table that contains several fields. We want to apply the following action on them
1- Add
2- Edit
3- Delete
Maybe this isn't the best practice, in short, my approach for this was to insert two spans for each data value:
One hidden that contains an input text field (inputSpan).
Another just contains plain text value (dataSpan).
Whenever you want to edit, dataSpan (just a data container) will disappear and inputSpan (text input field) appears instead enabling you to edit the text field. Once you edit and click Save the data in the text field will be cloned to replace the data in dataSpan. So basically dataSpan is just a reflection to inputSpan text field.
Here is an updated demo:
JSFiddle >> FullView Fiddle
I suggest for readability purposes, you break your code down into small function, it will make life easier, just sayin. So here general logic for your idea:
deleteRow = function (trID) {
// delete code goes here, remove the row
$(trID).remove();
}
manageEdit = function (tdNo) {
if ($("#edit-btn" + tdNo).html() === "Edit") {
$("#save-btn" + tdNo).show();//show save button
$("#edit-btn" + tdNo).html("Cancel");//change edit to cancle
editRow(tdNo);//call edit function
} else if ($("#edit-btn" + tdNo).html() === "Cancel") {
$("#save-btn" + tdNo).hide();//hide save button
$("#edit-btn" + tdNo).html("Edit");//change back edit button to edit
cancelEditRow(tdNo);
}
}
editRow = function (tdNo) {
$(".inputSpan" + tdNo).show();//show text input fields
$(".dataSpan" + tdNo).hide();//hide data display
}
cancelEditRow = function (tdNo) {
//looop thru 3 input fields by id last digit
for (var i = 0; i < 3; i++) {
//get input span that contain the text field
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
//get the data span that contain the display data
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
//text field inside inputSpan
var textField = inputSpan.find('input:text');
inputSpan.hide();//hide input span
textField.val(dataSpan.html());//take original data from display span and put it inside text field to cncle changes.
dataSpan.show();//show data span instead of edit field
}
}
saveRow = function (tdNo) {
//same as edit, but we reverse the data selection.
for (var i = 0; i < 3; i++) {
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
var textField = inputSpan.find('input:text');
inputSpan.hide();
dataSpan.html(textField.val());//take data from text field and put into dataSpan
dataSpan.show();
}
$("#edit-btn" + tdNo).html("Edit");//change text to edit
$("#save-btn" + tdNo).hide();//hide same button.
}
Here where I add the spans:
var tdCounter = 0;
$(".span4").each(function () {
var tid = val+"-"+tdCounter;
$tr.append("<td id='#mytd"+tid+"'>
<span id='inputSpan"+tid+"' class='inputSpan"+val+"' style='display:none'>
<input type='text' id='#input"+tid+"' value='"+ $(this).val() + "' /></span>
<span id='dataSpan"+tid+"' class='dataSpan"+val+"'>"+$(this).val()+"</td>");
tdCounter++;
});
Here I just append the buttons to call the functions, each button works for it's own row:
$tr.append("<td><botton id='edit-btn" + val + "' class='btn' onclick=manageEdit('" + val + "');>Edit</botton></td>");
$tr.append("<td><botton style='display:none' id='save-btn" + val + "' class='btn' onclick=saveRow('" + val + "');>Save</botton></td>");
$tr.append("<td><botton id='delete-btn" + val + "' class='btn' onclick=deleteRow('" + trID + "');>Delete</botton></td>");
Below is a sample function, it wont do everyhing you need, but it shows the jquery functions and one possibility how to do it. I only enabled editing name field, and deleting.
You would have to add other fields, + copy id data for the input.
js Fiddle
window.deleteRow = function (tar) {
$(tar).parent().remove();
}
window.editRow = function (tar) {
var row = $(tar).parent(),
cells, name;
cells = row.find("td");
name = $(cells.get(1)).text();
$(cells.get(1)).text('');
$(cells.get(1)).append('<input type="text" value="' + name + '">');
}
window.saveData = function() {
var data = {};
data.name = "some name";//get this from your input
data.email= "some email";//get this from your input
data.phone= "some phone";//get this from your input
$.get("http://yourphpsite.com", data, function(data, status) {
//data contains your server response
if (data.somepositiveservermessage) {
$("#user_notification_field").text("data saved");
$("#user_notification_field").show();
});
}

Categories