I have a template that will consists of 2 hidden fields and 1 checkbox. The template is rendered and appended to the html page using a function addProductImage().
How can I go about getting the value of the hidden fields (thisFile and mainImage)? The id of the div is dynamic gc_photo_{{id}}_{{filename}}, it look something like this gc_photo_1234_12dhbc.jpg .
After getting the value of the two hidden fields, I want to match the 2 values and see if it is ===, if is it will set the checkbox to checked.
Code for the template
<script type="text/template" id="imageTemplate">
<div class="row gc_photo" id="gc_photo_{{id}}_{{filename}}" style=" border-bottom:1px solid #ddd; padding-bottom:20px; margin-bottom:20px;">
<div class="col-md-2">
<input type="hidden" name="thisFile" value="{{filename}}"/>
<input type="hidden" name="mainImage" value="<?php echo $biz_product->image_name;?>"/>
<input onclick="return set_parentimage(this);" type="radio" name="primary_image" id="{{id}}_{{filename}}" value="{{id}}" {{#primary}}checked="checked"{{/primary}} /> <?php echo lang('main_image');?>
</div>
</div>
</script>
Code for the function
function addProductImage(val)
{
view = {
id:val.item_id.replace(/\s/g, ''),
filename:val.detail_image_name,
alt:val.alt,
primary:val.primary,
caption:val.caption
}
var output = Mustache.render(imageTemplate, view);
$('#gc_photos').append(output);
$('#gc_photos').sortable('refresh');
thisFile = $($('#gc_photo_id_filename').find("input")[0]).val();
mainImage = $($('#gc_photo_id_filename').find("input")[1]).val();
alert(thisFile);
alert(mainImage);
if(thisFile === mainImage)
{
alert('true');
}
else
{
alert("different");
}
photos_sortable();
}
}
Update 1
Code for the function
function addProductImage(val)
{
view = {
id:val.item_id.replace(/\s/g, ''),
filename:val.detail_image_name,
alt:val.alt,
primary:val.primary,
caption:val.caption
}
var output = Mustache.render(imageTemplate, view);
$('#gc_photos').append(output);
$('#gc_photos').sortable('refresh');
thisFile = $($('#gc_photo_id_filename').find("input")[0]).val();
mainImage = $($('#gc_photo_id_filename').find("input")[1]).val();
alert(thisFile);
alert(mainImage);
if(thisFile === mainImage)
{
$('[name="primary_image"]').prop('checked', true);
}
else
{
alert("different");
}
photos_sortable();
}
}
thisFile = $(output).find("[name='thisFile']").val();
mainFile = $(output).find("[name='mainFile']").val();
you can get values of thisFile and mainFile this way.
Related
In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.
How can I check the Number of Incomplete Input fields in Particular ID, (form1, form2).
If 2 input fields are empty, in i want a msg saying something like "Incomplete Input 2"
How is it Possible to do this in JS ?
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test">
<input type="text" value="">
</div>
This is the JS, which is working, i have have multiple JS with class named assigned to each inputs and get the value, but i need to make this check all the Input fields inside just the ID.
$(document).on("click", "#form1", function() {
var count = $('input').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
Your html structure, especially form structure is not correct, so you should first add some submit button to form that can be clicked. Then you can add event listener on form's submission. In the event handler you should select children inputs inside the form tag using $(this).children("input"). Now you can filter them.
$(document).on("submit", "#form1", function (e) {
e.preventDefault();
var count = $(this)
.children("input")
.filter(function (input) {
return $(this).val() == "";
}).length;
alert(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
<button type="submit">Submit</button>
</form>
This is the JS, which is working, if I have have multiple JS with class named assigned to each inputs and Im getting the value, but i have multiple JS for this to work.
How can i make this Simpler say like, when user clicks on Div, it only checks the input fields inside that div.
$(document).on("click", "#form1", function() {
var count = $('.input_field1').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
HTML
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="" class="input_field1">
<input type="text" value=""class="input_field1">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test" class="input_field2">
<input type="text" value="" class="input_field2">
</div>
See snippet below:
It has commented and if you put some effort on it, you can have a jQuery plugin out of it.
(function () {
'use strict';
var
// this use to prevent event conflict
namespace = 'customValidation',
submitResult = true;
var
input,
inputType,
inputParent,
inputNamePlaceholder,
//-----
writableInputTypes = ['text', 'password'],
checkboxInputType = 'checkbox';
var
errorContainerCls = 'error-container';
// Add this function in global scope
// Change form status with this function
function changeFormStatus(status) {
submitResult = submitResult && status;
}
// Check if a radio input in a
// group is checked
function isRadioChecked(form, name) {
if(!form || !name) return true;
var radio = $(form).find('input[type="radio"][name="' + name.toString() + '"]:checked');
return typeof radio !== 'undefined' && radio.length
? true
: false;
}
function eachInputCall(inp, isInSubmit) {
input = $(inp);
inputType = input.attr('type');
// assume that we have a name placeholder in
// attributes named data-name-placeholder
inputNamePlaceholder = input.attr('data-name-placeholder');
// if it is not present,
// we should have backup placeholder
inputNamePlaceholder = inputNamePlaceholder ? inputNamePlaceholder : 'input';
if(!inputType) return;
// you have three type of inputs in simple form
// that you can make realtime validation for them
// 1. writable inputs ✓
// 2. checkbox inputs ✓
// 3. radio inputs ✕
// for item 3 you should write
// another `else if` condition
// but you should have it for
// each name (it was easier if it was a plugin)
// radio inputs is not good for realtime
// unchecked validation.
// You can check radios through submit event
// let make it lowercase
inputType = inputType.toLowerCase();
// first check type of input
if ($.inArray(inputType, writableInputTypes) !== -1) {
if(!isInSubmit) {
input.on('input.' + namespace, function () {
writableInputChange(this);
});
} else {
writableInputChange(inp);
}
} else if ('checkbox' == inputType) { // if it is checkbox
if(!isInSubmit) {
input.on('change.' + namespace, function () {
checkboxInputChange(this);
});
} else {
checkboxInputChange(inp);
}
}
}
// Check if an input has some validation
// (here we have just required or not empty)
function writableInputChange(inp) {
// I use $(this) instead of input
// to prevent conflict if selector
// is a class for an input
if('' == $.trim($(inp).val())) {
changeFormStatus(false);
// your appropriate message
// you can use bootstrap's popover
// to modefy just input element
// and make your html structure
// more flexible
// or
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(inp).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please fill ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(inp).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
// Check if an checkbox is checked
function checkboxInputChange(chk) {
if(!$(chk).is(':checked')) {
changeFormStatus(false);
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(chk).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please check ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(chk).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
$(function () {
var
form = $('#form'),
// you can change this selector with your classes
formInputs = form.find('> .input-group > input');
formInputs.each(function () {
eachInputCall(this);
});
form.submit(function () {
submitResult = true;
// check all inputs after form submission
formInputs.each(function () {
eachInputCall(this, true);
});
// Because of radio grouping by name,
// we should select them separately
var selectedGender = isRadioChecked($(this), 'gender');
var parent;
if(selectedGender) {
changeFormStatus(true);
parent = $(this).find('input[type="radio"][name="gender"]').parent();
parent.children('.' + errorContainerCls).remove();
} else {
changeFormStatus(false);
// I assume that all radios are in
// a separate container
parent = $(this).find('input[type="radio"][name="gender"]').parent();
if(!parent.children('.' + errorContainerCls).length) {
parent.append($('<div class="' + errorContainerCls + '" />').text('Please check your gender'));
}
}
if(!submitResult) {
console.log('There are errors during validations!');
}
return submitResult;
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<div class="input-group">
<input type="text" name="input1" data-name-placeholder="name">
</div>
<div class="input-group">
<input type="checkbox" name="input2" data-name-placeholder="agreement">
</div>
<div class="input-group">
<input type="radio" name="gender">
<input type="radio" name="gender">
</div>
<button type="submit">
submit
</button>
</form>
Good day all,
I have the following html code
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
and, I have the following javascript code
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia =
'<div class="blog_comm_hold"> \
<div class="user_comment_photo1"></div> \
<div class="blog_comment_"> \
<div class="blog_com_text">\
comment\
</div>\
</div>\
<br>\
</div>';
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
</script>
What I am trying to do is have the value that I typed into the textarea field of the form be displayed after the form when the user hits the enter key. The div classes load well but I don't know how to go about getting the actual value from the var variable be displayed too.
The var comment variable as can be seen above is not displaying its value. The variable is found under the blog_com_text div in the above script.
I want that when the user hits the enter key, that the value of the above comment variable is loaded inside of the respective div based on the above code. The div classes load well with no issue but how to have the value of the variable be loaded too.
Thanks much.
Here you go with the solution https://jsfiddle.net/xabt3vgt/
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
//$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
// function(data) {
var newmedia =`<div class="blog_comm_hold">
<div class="user_comment_photo1"></div>
<div class="blog_comment_">
<div class="blog_com_text">
${comment}
</div>
</div>
<br>
</div>`;
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
//});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
You just need to uncomment you php ajax call.
Use back tick ` (left to 1) in the keyboard and if you want to add any variable then use ${variable_name} in between the back tick.
Try this
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment));
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
You can test with this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="post_blog_comment"></div>
<textarea id="blog_comment"></textarea>
<input type="button" value="Go" id="postcomment" />
<script type="text/javascript">
$('#postcomment').click(function() {
showcomment();
});
function showcomment() {
var comment = $("#blog_comment").val();
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment);
$('#post_blog_comment').after(newmedia);
$("#blog_comment").val('');
}
</script>
Here are the radios and textarea etc.
if(mysql_num_rows($canview) > 0) { ?>
<!-- Questions on return send all this to database then to place where dept. heads can see it-->
<div id = "returnform" >
<form action="" method="post">
<h4>Are any of the item(s) missing?</h4>
Yes<input type ="radio" name ="missing" id = "missing1" value = "Yes" required>
No<input type ="radio" name ="missing" id = "missing2" value = "No" >
<div class = "lossnum">
<input type="number" name="lossnum" id = "lossnum" placeholder="0">
</div>
<h4>Was every item put back/plugged in correctly?</h4>
Yes<input type ="radio" name ="putback" id = "putback1" value = "Yes" required>
No<input type ="radio" name ="putback" id = "putback2" value = "No">
<div class = "returncomments">
<h4>what happened?</h4>
<textarea name="comments"></textarea>
</div>
</div>
<input name="item_id" type="hidden" value="<?php echo $item->get_id(); ?>" />
<h4>Are you sure you want to return these <?php echo $item->get_name(); ?>? </h4>
<input type="submit" id="submit" name="submit" value="Return" />
right now all i have to change this is this:
$(document).ready(function () {
$(".lossnum").hide();
$(".comments").hide();
$(".returncomments").hide();
$(".commentup").hide();
$("#missing1").click(function () {
$(".lossnum").show();
$(".comments").show();
$(".returncomments").show();
});
$("#missing2").click(function () {
$(".lossnum").hide();
if($('#putback2').is(':checked')){
$(".comments").show();
$(".returncomments").show();
}
else{
$(".comments").hide();
$(".returncomments").hide();
}
});
$("#putback2").click(function () {
$(".comments").show();
$(".returncomments").show();
});
$("#putback1").click(function () {
if($('#missing2').is(':checked')){
$(".comments").hide();
$(".returncomments").hide();
}
else{
$(".comments").show();
$(".returncomments").show();
}
});});
this makes it so the textarea opens if 1 is yes and/or 2 is no, the only problem is if you then change the radios to no1/yes2 (which should be the only way the textarea does not show) it stays there, how would i make it so that it only shows up when something other than yes for 1 and/or no for 2 is true, and if that is changed it goes away and if it is not true does not show up.
Next I would like to make is so that when either 1 = Yes or/and 2 = no , the textarea is required to be filled out
you can for the most part ignore lost num
here is a JSfiddle for it
var itemMissing = false
, itemPluggedIn = true;
function updateCommentsDisplay(itemMissing, itemPluggedIn) {
if(itemMissing || !itemPluggedIn) {
$('#comments').show();
} else {
$('#comments').hide();
}
}
$('#nb-of-missing-items-field').hide();
updateCommentsDisplay(itemMissing, itemPluggedIn);
$('#missing input[name="missing-items"]').on('change', function () {
if(this.value === 'Yes') {
$('#nb-of-missing-items-field').show();
itemMissing = true;
} else {
$('#nb-of-missing-items-field').hide();
itemMissing = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
$('#plugged-in input[name="plugged-in-items"]').on('change', function () {
if(this.value === 'Yes') {
itemPluggedIn = true;
} else {
itemPluggedIn = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
http://jsfiddle.net/L7et15du/7/
Is that what you want to achieve?
On page 1, I have a div containing information.
<div id='information'></div>
And on page 2, I have a form with a textarea and a button.
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
Now what I want is when I click the submit button, the text inputted in the text area will be posted in div#information changing its previous content.
I have seen many other post on how to change div content, but those were unrelated to my problem.
One way is to do like what the other answers mentioned, to have each tab communicate to a central server that will get/send data to keep both tabs updated using AJAX for example.
But I'm here to tell you about another way though, it's to use what we already have designed for this kind of task exactly. What so called browser localStorage
Browser storage works like this pseudo code:
//set the value, it works as a hash map or assoc array.
localStorage .setItem("some_index_key", "some data") ;
// get the value by it's index key.
localStorage .getItem("some_index_key") ; // will get you "some data"
Where all the data will be shared among all open tabs for the same domain. And you can add event listener so whenever one value change, it will be reflected on all tabs.
addEvent(window, 'storage', function (event) {
if (event.key == 'some_index_key') {
output.innerHTML = event.newValue;
}
});
addEvent(myInputField, 'keyup', function () {
localStorage.setItem('some_index_key', this.value);
});
Check out this DEMO, you edit one field on page-A, and that value will be reflected on page-B offline without the need to burden the network.
To learn more, read this.
Real live example. The background color is controlled from another tab.
var screenone = document.getElementById('screenone');
screenone.addEventListener('keydown', screenOneFunction);
screenone.addEventListener('change', screenOneFunction);
function screenOneFunction()
{
document.body.style.backgroundColor = this.value;
localStorage.setItem("color1", this.value);
}
var screentwo = document.getElementById('screentwo');
screentwo.addEventListener('keydown', function (evt) {
localStorage.setItem("color2", this.value);
});
screentwo.addEventListener('change', function (evt) {
localStorage.setItem("color2", this.value);
});
var thebutton = document.getElementById('thebutton');
thebutton.addEventListener('click', function (evt) {
localStorage.clear();
screenone.value = "";
screentwo.value = "";
document.body.style.backgroundColor = "";
});
var storageHandler = function () {
document.body.style.backgroundColor = localStorage.color2;
var color1 = localStorage.color1;
var color2 = localStorage.color2;
screenone.value = color2;
screentwo.value = color1;
};
window.addEventListener("storage", storageHandler, false);
.screenone{ border: 1px solid black;}
input{ margin: 10px; width: 250px; height: 20px; border:round}
label{margin: 15px;}
<html>
<head>
</head>
<body>
<label> Type a color name e.g. red. Or enter a color hex code e.g. #001122 </label>
<br>
<input type="text" class="screenone" id="screenone" />
<label> This tab </label>
<br>
<input type="text" class="screentwo" id="screentwo" />
<label> Other opned tabs </label>
<br>
<input type="button" class=" " id="thebutton" value="clear" />
</body>
</html>
Hope this will give you an idea of how you can do it:
Page 2
HTML
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
JS
$("form").submit(function(e){
e.preventDefault();
$.post('save_data.php', { new_info:$("#new-info").val() }).done(function(data){
// Do something if you want to show that form has been sent
});
});
save_data.php
<?php
if (isset($_POST['new-info'])) {
// Update value in DB
}
?>
Page 1
HTML
<div id='information'>
</div>
JS
setInterval(search_after_info, 1000);
function search_after_info() {
$.get('get_data', function(data) {
$("#information").html(data);
});
}
You mean some thing like this ?
$("#submit-info").click(function() {
var content = $("#new-info").text();
$("#information").html(content);
});
If you thing about server side, tell more about technology, which you use.
This is exactly as the following:
Page 1:
<form action="test2.htm" method="get">
<textarea name ='new-info'></textarea>
<input type = 'submit' id='submit-info' value ='pass' onclick="postData();"/>
Page 2
<div id="information"></div>
<script>
if (location.search != "")
{
var x = location.search.substr(1).split(";")
for (var i=0; i<x.length; i++)
{
var y = x[i].split("=");
var DataValue = y[1];
document.getElementById("information").innerHTML = DataValue;
}
}
</script>