How do I access input name in php code through Javascript? - javascript

I have a PHP form with some rows. These rows have fields which look like this:
<input type="text" name="addresses[n][0]" value="mail " id="address" class="validate">
I have the following code in Javascript to add and and delete rows:
$(document).ready(function () {
$('select').material_select();
});
$(function ()
{
$(document).on('click', '.btn-add', function (e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
}).on('click', '.btn-remove', function (e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
My problem is, that after sending this form in POST with added rows, the added ones have the same 'n' index, because they are cloned. How can I access the 'name' attribute of them in the newEntry variable, which is a div of the whole row?
I have tried things like
newEntry.find('name').val('addressesNewName')
newEntry.find('input').getAttribute('name') = 'addressesNewName'
newEntry.find('name').setAttribute("name","addressesNewName");
newEntry.find('input').find('name').val('addressesNewName');
newEntry.find('input').attr('name') = 'newaddresses';
newEntry.find('input').attr('name').val('newaddresses');
But nothing changes the name in the field.
I don't need help with what n values to assign and so on, only how to change the name of the input field.

Have you tried?
newEntry.attr('name', 'addressesNewName');
Since you're using jQuery, accessing node attributes is easily done via:
$(node).attr('attributeName'); // get attribute value
$(node).attr('attributeName', 'newValue'); // set attribute value
jQuery API

Related

How do I add radial/checkbox values to an object using jQuery?

So I'm trying to iterate through all the values of an HTML form and store them in a hashtable object of sorts.
The HTML for the form is pretty lengthy so I won't paste that here. But here is my JavaScript/jQuery so far:
readForm = function () {
var formValues = {};
$('form :input').each(function () {
var input = $(this);
formValues[input.attr('name')] = input.val();
});
console.log(formValues);
}
When I put these values in the form:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsa_z9re1e.png
I get this in the console:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsafsdaf_tmdib6.png
Why is the value on the radial and checkbox inputs incorrect? And what is that last undefined property?
For checkboxes you can use this:
Option 1:
$('#checkbox_id').prop('checked'));
Option 2:
$('#checkbox_id').is(':checked'));
Maybe in your case with the loop you can try this:
if(input.attr('type') == 'checkbox') {
input.is(':checked'));
}
...
The undefined property is maybe the Submit button. Is it like this?
<input type="submit" value="Submit Profile">

add more button dont work in wordpress dashboard

im working on custom post in wordpress, in this custom post i wanna add many photos using wp_attachment the problem im having here is that when i click addmore nothing happen, its like if wordpress is ignoring my jquery file
my code
<div class="col-sm-9">
<input type="file" name="aduploadfiles[]" id="uploadfiles2" size="35" class="form-control" />
<input type="button" id="add_more2" class="upload" value="add more photo"/>
</div>
and this is the javascript im using
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more2').click(function() {
$(this).before($("<div/>", {id: 'uploadfiles2'}).fadeIn('slow').append(
$("<input/>", {name: 'aduploadfiles[]', type: 'file', id: 'aduploadfiles',size:'35', class:'form-control'})
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
this works fine when i try it in a wordpress pages but in dashboard itdoesn't want to work even my javascript is loaded
There are several issues:
1. $ is not available. Use jQuery
In WordPress, jQuery runs in compatibility mode, i.e. the $ shortcut is not available. You can solve this by capturing jQuery as function argument in the ready method, like this:
jQuery(document).ready(function($) {
The rest of the code in the ready callback can then continue to use $.
2. Wrong selector for file upload input element
You mentioned the wrong id in the jQuery selector: your file upload element has id uploadfiles2, not file. So change:
$('body').on('change', '#file', function(){
To:
$('body').on('change', '[name="aduploadfiles[]"]', function(){
3. Duplicate id values
Each time when you add a new button, you create a div with an id of uploadfiles2: but that id already exists. In HTML id values must be unique, otherwise unexpected things happen.
All the elements you create dynamically should get a dynamically created (distinct) id value (or no id at all).

Getting values of hidden checkboxes jQuery

I have a form with several checkboxes. Some values need to be true by default so i have made them hidden as:
<input type=checkbox name="<%= _key %>" checked="checked" style="display:none" />
To retrieve all values i'm doing:
var form_data = {}
$('form').find("input").each(function(i, e) {
if (e.checked)
form_data[e.name] = e.value;
});
But the hidden input fields are not coming. What am I doing wrong? How can I correct it?
Also im using underscore.js but i don't think this problem has to do anything with it.
For simplicity you can do this:
$(function(){ // put the code in doc ready
var form_data = {}
$('form').find(":checkbox:checked").each(function(i, e) {
form_data[e.name] = e.value;
});
});
So here i am suggesting you to just loop through the checked elems and put names & values in the javascript object.
But if you are interested in only hidden checked checkboxes $('form').find(":checkbox:checked:hidden").
I think you should do this jQuery way.
$('form').find("input").each(function(i, e) {
var jEl = $(this);
if(jEl.is(":checked"))
alert(1);
alert(jEl.attr("name"));
});

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

Categories

Resources