Changed value not showing - javascript

I've created a textfield to change a value, which seems to work fine on one part.
Voornaam: <h3 id="title1">Test</h3>
<input type="text" id="myTextField1"/>
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
This is linked to this javascript function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title1');
title.innerHTML = myNewTitle;
}
And this works without any problems and shows my changed value, however when I would like to display that same value somewhere lower in my html code, it does not show the changed value.
Here is a part of the code where the changed value does not show up:
<section class="bg-green">
<div class="block left wide">
<article>
<h1>testfile<br/><span contenteditable="true" data-id="school-name"><?php echo $schoolName; ?></span></h1>
<br/>
<p>
<strong>Geachte <span data-id="name"><?php echo $salutation; ?> <?php echo $lastName; ?></span></strong>,
<p id="title1">Test.</p>
</p>
The part where it should show up is
<p id="title1">Test.</p>
Could anyone point me in the right direction?

It seems that your are using the id "title1" more than once. The document.getElementById will only find one (the first, if I'm not mistaken).
Use a class and iterate over the elements found by getElementByClassName
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
Here is a working jsfiddle of my solution.

You have two DOM elements with the same ID = title1
<h3 id="title1">Test</h3>
and
<p id="title1">Test.</p>
entered text should appear in the first usage of ID = h3 tag.
It is also invalid HTML when you use one ID more times
The solution:
Voornaam: <h3 id="title1">Test</h3>
<input type="text" id="myTextField1"/>
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('change1result');
title.innerHTML = myNewTitle;
}
<section class="bg-green">
<div class="block left wide">
<article>
<h1>testfile<br/><span contenteditable="true" data-id="school-name"><?php echo $schoolName; ?></span></h1>
<br/>
<p>
<strong>Geachte <span data-id="name"><?php echo $salutation; ?> <?php echo $lastName; ?></span></strong>,
<p id="change1result">Test.</p>
</p>

Related

php pdo to insert array dynamically into database

I have been trying solve this for a while. I am new to php. Please help me to solve this.
I have form in which we can add more input fields whose values are added into an array 'array_names'. The php code i used adds values of added input filds into different 'id' in database. But I want add all input field values into single 'id' so than all values comes in single database table row. Please tell me how to do that.
Thanks in advance!
//form
<form action="" method="POST">
<div class="form-group">
<label for="PlanTitle"> <span class="FieldInfo"> Plan Title: </span></label>
<input class="form-control" type="text" name="PlanTitle" id="PlanTitle" placeholder="Type here" value="">
</div>
<div class="form-group">
<label for="SubTitle"> <span class="FieldInfo"> Plan Sub Title: </span></label>
<input class="form-control" type="text" name="SubTitle" id="SubTitle" placeholder="Type here" value="">
</div>
<div class="form-group">
<label for="SectionContent"> <span class="FieldInfo"> Features List </span></label>
<div class="input_fields_wrap">
<button class="add_field_button">Add More</button>
<input type="text" name="items[name][]">
</div>
</div>
<button type="submit" name="submit" class="inner">Submit</button>
</form>
//script
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e)
{
e.preventDefault();
if(x < max_fields)
{
x++; //text box increment
$(wrapper).append('<input type="text" name="items[name][]">');
}
});
});
</script>
//php code
if(isset($_POST["Submit"])){
$Id = $_SESSION["id"];
$PlanTitle = $_POST["PlanTitle"];
$SubTitle = $_POST["SubTitle"];
$items = (isset($_POST['items']) && is_array($_POST['items'])) ? $_POST['items'] : array();
$array_names = $items['name'];
global $ConnectingDB;
foreach ($array_names as $name) {
$sql = "INSERT INTO plan(title,subtitle,items);
$sql .= "VALUES(:planTitle,:SubTitle,:Items);
$stmt = $ConnectingDB->prepare($sql);
$stmt->bindValue(':planTitle',$PlanTitle);
$stmt->bindValue(':subTitle',$SubTitle);
$stmt->bindValue(':name', $name);
$Execute=$stmt->execute();
}
Plan Table
Current Output
id
title
subtitle
items
1
title1
subtitle1
item1
2
title1
subtitle1
item2
3
title1
subtitle1
item3
Expected Output
id
title
subtitle
items
1
title1
subtitle1
item1,item2,itme2
As a general rule, if you ever find yourself trying to save an array in a db column, you are probably better off creating a new table for that array, where each element of the array gets its own record, and become friendly with INNER JOIN. A quick search will turn up numerous tutorials and examples on INNER JOIN, including many on this site.
If you absolutely must save the array into a column of a record, do what those leaving comments suggest.

Javascript getElementById when you dont know the ID

I am using PHP to assign a random ID to a checkbox, now I want to check that value of checkbox but because I don't know the ID, I dont know how to check it.
so here is the HTML :
<input class="citycheck"
id="<?php $city_id; // this is randomly generated ?>"
type="checkbox"
name="<?php echo $city_name"> <?php echo $city ?>
<div class"properties">Some Properties</div>
and my Javascript:
<script>
jQuery(document).ready(function($) {
// right now I am checking by class
// show or hide if it is already checked
if ($(".citycheck").is(':checked'))
$(".properties").show();
else
$(".properties").hide();
// show or hide if user clicked on the checkbox
$(".citycheck").click(function() {
if ($(this).is(":checked")) {
$(".properties").show();
} else {
$(".properties").hide();
}
});
});
</script>
but because there are many checkbox with class citycheck when one is checked, if another city is not checked, the properties are still shown.
How can I check the value of checkbox by ID when I don't know the ID yet?
Update
The reason I want the ID is because ID is unique and class is not. So using class, if one checkbox is checked it shows properties related to that class.
I have a checkbox for every city, every city had some properties, if I click on Chicago, then properties of Chicago are listed. Problem right now is that if I check Chicago, properties of Boston are also shown.
You could assign a pseudo class in your element and use this pseudo class to find all the elements in your page. Then you can check which of them are checked and do whatever is needed. I did the same also for details by assigning a pseudo class. As it is now your html code if someone change the name of the class from citycheck to whatever the behavior of you UI will not change at all, provided that will note move the elements, since we rely on the siblings. Please have a look at the following snippet:
$(function(){
$('.js-citicheck').on("change", function(){
var ele = $(this);
var details = ele.siblings('div.js-details');
if(ele.is(":checked")){
details.show();
} else {
details.hide();
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="citycheck js-citicheck"
id="berlin"
type="checkbox"
/>
<label for="berlin">Berlin</label>
<div class="details js-details" style="display:none">Berlin details.</div>
</div>
<div>
<input class="citycheck js-citicheck"
id="london"
type="checkbox"
/>
<label for="london">London</label>
<div class="details js-details" style="display:none">London details.</div>
</div>
<div>
<input class="citycheck js-citicheck"
id="paris"
type="checkbox"
/>
<label for="paris">Paris</label>
<div class="details js-details" style="display:none">Paris details.</div>
</div>
You Can add a prefix to the id
<input class="citycheck"
id="<?php echo 'id_'.$city_id; ?>" // this is randomly generated
type="checkbox"
name="<?php echo $city_name"> <?php echo $city ?>
<div class"properties">Some Properties</div>
and then :
var list = document.querySelectorAll('[id^="id_"]');
var list = $('[id^="id_"]');
traverse the list and check if it's checked or not
I think you can achieve everything you want to with simple jQuery selectors.
Working Example:
$(document).ready(function(){
$('.properties').hide();
$('.citycheck:checked + .properties').show();
$('.citycheck').change(function(){
$(this).next('.properties').toggle();
alert('The id of this checkbox is: ' + $(this).attr('id'));
});
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sdnflfldja" class="citycheck" type="checkbox" name="Alphaville">
<div class="properties">Some Properties</div>
<input id="sdnfldfj" class="citycheck" type="checkbox" name="Betaville">
<div class="properties">Some Properties</div>
<input id="szdnnadsc" class="citycheck" type="checkbox" name="Gammaville">
<div class="properties">Some Properties</div>
<input id="sallddfa" class="citycheck" type="checkbox" name="Deltaville">
<div class="properties">Some Properties</div>
<input id="adlkfkfddsl" class="citycheck" type="checkbox" name="Epsilonville">
<div class="properties">Some Properties</div>

How to get the input value from $(this).context

My Full calender external events are displayed as following
<?php foreach ($plants as $plant) { ?>
<div class='fc-event evt'>
<input type="hidden" value="<?php echo $plant->hcpd_id;?>" class="abc">
<p class="evt_name"><?php echo $plant->hcpd_name;?></p>
</div>
<?php } ?>
And this is my jquery
$('#external-events2 .fc-event').each(function() {
var str = $(this).context;
$(this).data('event', {
title: $.trim($(this).text()),
stick: true,
color : '#4AC948',
className : "sub",
id : //need to add the id here
});
});
I want to give a specific id to each event. (taken from the database. It is given in the hidden input field)
Following is one of the generated divs.
I want to get the hidden id of the following $(this).context result
<div class="fc-event evt ui-draggable ui-draggable-handle">
<input type="hidden" value="1" class="abc">
<p class="evt_name">My Plant 1</p>
</div>
Any idea of how to retrieve that.
I tried string replacing, but didn't work.
What event are you using? For example, if you are using the click event:
$('.fc-event').click(function(){
//Get the ID
var eventID = $(this).find('input[type="hidden"]').val();
//Do whatever you want with the ID here.
});

How to make a slider bar

Aloha, I'm trying to develop a slider bar that has 3 words that you can choose from. But I'm not able to save the words as letters, all I get is number either 1,2 or 3 :(
Here's the code I have and also a picture:)
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider">
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but"/>
</input>
</form>
So this code shows the slider bar and letters at the top (which works with my css), but when I click "Submit", on the following page (using php) I get 1, 2 or 3.
But it should be Bad, Good or Good. I'm sure that the problem is in the HTML code.
Why not just assign the numerals to values when you process the submission?
if(isset($_POST['slider'])) {
$array[1] = 'Bad';
$array[2] = 'Ok';
$array[3] = 'Good';
// This is a simplified output, but this is essentially
// the easiest way
echo $array[$_POST['slider']];
}
There is two manner to do what you want :
1 - html + javascript :
You should add a hidden input in your form which before submitting your form you give it a value among the three : Bad, OK, Good according to the value of your slider.
2 - php :
<?php
$slider_index = intval($_POST['slider']);
$word = '';
switch ($slider_index) {
case 1:
$word = 'Bad';
break;
case 2:
$word = 'OK';
break;
case 3:
$word = 'Good';
break;
}
?>
This is not possible by using html only.
You could create a hidden input field and a "change" event handler on the range input field. The event handler sets the value of the hidden input field to the label corresponding to the selected number (1: bad, 2: ok, 3: good).
Example:
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider" id="slider">
<input type="hidden" name="sliderLabel" id="sliderLabel" />
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but" />
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
(function() {
// function to update the value of the hidden field
updateSliderLabel = function() {
var selectedValue = $('#slider').val();
var selectedLabel = $('#text > span').eq(selectedValue-1).text();
$('#sliderLabel').val(selectedLabel);
}
// when slider is changed, call the update function
$('#slider').on('change', function() {
updateSliderLabel();
});
// when page is loaded, call the update function
updateSliderLabel();
})();
</script>
The advantage of this solution is, you can easily adopt your labels in the html code, you don't need to modify your php logic.

How to get Elements values inside element with class

Below code is created from my DB so its multiple with same classes name but with different contents.
What i need to do is that when button with class = 'config' is clicked i need to get the values ['value','type','info'] of this div with this class = config .
How would i go ahead with this ?
$(".config").click(function(){
var id = $(this).attr('id');
});
Any Hint ??
HTML
<div class="mws-form-row bordered">
<label class="mws-form-label"><?php echo SaleAdmin_Engine::getConfigName($this->result[0]['config_name']) ; ?></label>
<div class="mws-form-item">
<b>Value</b> <input type="text" class="value required large" value="<?php echo $this->result[0]['config_value']; ?>">
<b>Type</b> <input type="text" class="type required large" value="<?php echo $this->result[0]['config_type']; ?>">
<b>Info</b> <textarea rows="" cols="" class="info required large"><?php echo $this->result[0]['config_info']; ?></textarea>
</div>
<button class="config btn btn-inverse btn-small" rel="<?php echo $this->result[0]['config_id']; ?>" type="button">Save</button>
</div>
If I understand you correctly something like this should work for you
$(".config").click(function(){
var form1 = $(this).parent();
var value = form1.find(".value").value();
var type = form1.find(".type").value();
var info = form1.find(".info").value();
});
The this in your selector is referencing the button which does not have the elements you are looking for. In order to get those elements you need to get the parent form that the button is related to.
$(document).ready(function(){
$(".config").click(function(){
var form1 = $(this).parent();
var value = form1.find(".value").val();
var type = form1.find(".type").val();
var info = form1.find(".info").val();
});
});
Here is a working jsfiddle.
You can get a collection using the jQuery class selector and then iterate over them all in one shot using jQuery map function to build your values.
$(".config").click(function(){
//Get all items with required class
var resultArray = $.map($(".required"), function(val){
return val.value;
});
console.log(resultArray);
});
See it in action in this fiddle

Categories