How to get Elements values inside element with class - javascript

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

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.

How to make content editable with button

I am trying to make the input type text field editable on click with button but it is not working properly. tried all possible thing any suggestion please
<html><body>
<script>
$(document).ready(function()
{
$('#btnEdit').click(function()
{
$("input[name='name']").removeAttr("readonly");
});
});
</script>
<?php
require_once ('connectdb.php');
$sql = "SELECT * FROM general_information";
$result = $dbhandle->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form>
<input type = "text" name = "name" value = <?php echo $row["email"];?> readonly>
<button class="btn btn-primary" id="btnEdit" > edit </button>
<?php } } ?>
</form>
</body></html>
There are two problems I see in the code,
Button is submitting the form and reloading the page. Use preventDefault() to override form submit.
Use prop instead of removeAttr.
$(document).ready(function(){
$('#btnEdit').click(function(e){
e.preventDefault();
$("input[name='name']").prop("readonly", false);
});
});
UPDATE from #cmorrissey comment.
In textbox, quotes are missing in the value attribute
<input type = "text" name = "name" value = "<?php echo $row["email"];?>" readonly>
Your button is posting the form thus reloading the page so Change your button and give it an onclick event function like onclick="editInputField()":
Edit
Give the input and id:
<input type = "text" id = "name" name = "name" value = <?php echo $row["email"];?> readonly>
Then your javascript function to make the input editable:
<script type="text/javascript">
function editInputField(){
document.getElementById("name").readOnly = false;
}
</script>
EDIT
I noticed you using jquery even though the question is tagged with javascript.
The reason why your code is not working has to do with:
1: The button as mentioned earlier so change it to:
Edit
2: How your targeting the input field, use the field id like this:
$("#fieldID").removeAttr("readonly");
You can use disable or readOnly attributes. Here you have two examples.
<input type="text" id="name" disabled="disabled" value="Example"/>
<input type="text" id="name2" readonly="readonly" value="Example2"/>
<button onclick="myFunction()">Click me</button>
function myFunction() {
document.getElementById("name").disabled = false;
document.getElementById("name2").readOnly = false;
}

Changed value not showing

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>

getting css style property using javascript

I have a image draggable and would like to save it via PHP so I decided to get the inner style and put it as value in input field, so I can get it via $_POST, but I am unable to find like if it would be a inner HTML data I could have get it via calling innerHTML syntax, but like so is there any way of getting style for the image
<div class="scott_img">
<img id="uploadPreview" src="<?php echo (empty($data['profile_pic'])) ? "images/profile.jpg" : "uploads/" . $data['profile_pic']; ?>" style="style goes here">
<span class="scouttag"></span>
</div>
<form method="POST" action="profile.php?uid=<?php echo $uid; ?>" enctype="multipart/form-data" style="text-align:center;">
<input id="uploadImage" type="file" name="image" style="margin:auto;" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="uploadPreview1" value="need style here so i can save it to database" />
<button type="submit" name="update_picture" class="btn_form">Update Picture</button>
</form>
<img class="scott_line"src="images/line.png">
<script>
(function() {
var elem = document.getElementById('uploadPreview');
var val = getComputedStyle(elem);
document.getElementById('uploadPreview1').value = val;
var $section = $('.scott_img').first();
$section.find('#uploadPreview').panzoom({
$zoomRange: $section.find(".zoom-range"),
$reset: $section.find(".reset")
});
})();
</script>
Thank you
if you get element style tag (inline css)
var a = document.getElementById('uploadPreview');
var b= a.getAttribute('style');
alert(b);
if you get element css
var element = document.getElementById('uploadPreview'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
I'm not sure how and why you are going to use this server-side, but if you believe that's the right thing to do, just stringify the JSON object:
var val = JSON.stringify(getComputedStyle(elem));
You can get an element's CSS style in JS and transform it into JSON like so:
var elementCSS = JSON.stringify(document.getElementById('uploadPreview').style)
since the Css value is in an input you have to get it via:
Var x = Document.getElementById("").value
Then in your java script, append the Css rules by doing;
X.style.width = Y;
Or div.style.color = "#ccc";
Hope you get the point
Can't you use simple jQuery to get style value like below?
var imgstyle = $("#uploadPreview").attr("style"); //this will get your whole value of style attribute.
$("#uploadPreview1").val(imgstyle); //this will update hidden field's value.
also it seems that it is going to be different on each upload. So you can put this above code inside your draggable or file uplaod's change event.

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.
});

Categories