I am using form to pass the data from one page to other page.If i click the apply button will go to other page, i want to display the corresponding title of the career(i.e Java Developer) in the next page.I tried to achieve this with the help of javascript.
career.html:
<form action="job portal.html" method="get" target="_blank">
<div class="section-header text-center wow zoomIn">
<h2>Current Oppournities</h2>
</div><br /><br />
<div class="row">
<div class="col-lg-6">
<div class="box wow fadeInLeft">
<h4 class="title" id="career-title" name="career-title"><i class="fa fa-java"></i> <b>Java Developer</b></h4>
<hr />
<div class="carrer-opt">
<h5 name="test">Software Developer</h5>
<p>
Should have join immediate joiner .
</p>
</div>
<div class="col-lg-3 cta-btn-container">
<input type="submit" id="apply" value="Apply Now" onClick="testJS()" />
</div>
</div>
</div>
</form>
js:
<script src="js/main.js"></script>
<script>
function testJS() {
var b = document.getElementById('career-title').value,
url = 'job portal.html?career-title=' + encodeURIComponent(b);
document.location.href = url;
}
</script>
job portal.html:
<h1 id="here" style="color:black"></h1>
js:
<script>
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.career-title;
}
</script>
How to acheive this.Anyone please help.
You need to use HTML5 local storage for these kind of problems.
here is solution for your problem.
<script>
function testJS() {
var b = document.getElementById('career-title').value;
var titleText = localStorage.setItem('title', b);
var url = 'job portal.html';
document.location.href = url;
}
</script>
after setting title value get value by referencing id 'title' in your prtal.html script and set value for the element.
<script>
window.onload = function () {
var valueText = localStorage.getItem('title');
document.getElementById('here').innerHTML = valueText;
}
</script>
Related
I am pulling data from MySQL database and displaying user posted content on the page. A UserPost consists of data from 2 tables, UserTable and PostTable.
When querying from both tables I have the correct information displayed until I click the edit button. Then the queried data inside the popup always matches the first element of the query. I believe this is because the popup has an ID. I tried using PHP data to have multiple buttons with different IDs but I am still getting the same popup content correlating with the first queried data. I have highlighted the lines in question with "<-- PROBLEM HERE**********************************"
Thank you.
PHP Function Calling All User Posts
function homePosts($conn) {
$UserID = $_SESSION['UserID'];
$userPostSQL = "SELECT * FROM PostTable WHERE UserID = ? AND SectionID = 1 ORDER BY Date DESC";
$userPostSTMT = $conn->prepare($userPostSQL);
$userPostSTMT->bind_param("s", $UserID);
$userPostSTMT->execute();
$userPostRESULT = $userPostSTMT->get_result();
if (mysqli_num_rows($userPostRESULT) != 0) {
// User Posts Exist
while ($userPostROW = $userPostRESULT->fetch_assoc()) {
$userInfoSQL = "SELECT UserName, ProfilePicture FROM UserTable WHERE UserID = ?";
$userInfoSTMT = $conn->prepare($userInfoSQL);
$userInfoSTMT->bind_param("s", $UserID);
$userInfoSTMT->execute();
$userInfoRESULT = $userInfoSTMT->get_result();
if (mysqli_num_rows($userInfoRESULT) != 0) {
// User Info Exists
while ($userInfoROW = $userInfoRESULT->fetch_assoc()) {
$Date = $userPostROW['Date'];
$Text = $userPostROW['Text'];
$PostID = $userPostROW['PostID'];
$UserName = $userInfoROW['UserName'];
$ProfilePicture = $userInfoROW['ProfilePicture'];
echo '
<div class="popup" id="popup-'.$PostID.'"> <-- PROBLEM HERE $PostID remains the same throughout the loop**********************************
<div class="overlay"></div>
<div class="content">
<div class="close-btn" onclick="togglePopup()">×</div>
<h1>Edit Post</h1>
<p>'.$Text.'</p>
<p>This Post ID keeps the value of the first loop iteration'.$PostID.'</p>
</div>
</div>
<div class="postBox">
<img class="postprofilepicture" src="../profilepictures/'.$ProfilePicture.'">
<p class="postusername">'.$UserName.'<p>
<p class="posttime">'.date('M jS, Y h:ia',strtotime($Date)).'<p>
<p>'.$Text.'</p>
<p>This Post ID Changes through for every new row'.$PostID.'<p>
<br>
<div class="dropdown">
<button onclick="myFunction(this)" class="dropbtn">···</button>
<div Id="myDropdown" class="dropdown-content">
View
Like
Save
Edit
<button onclick="togglePopup()">Popup</button>
</div>
</div>
</div>
<br>
<script>
function togglePopup(){
document.getElementById("popup-'.$PostID.'").classList.toggle("active"); <-- PROBLEM HERE $PostID remains the same throughout the loop**********************************
}
function myFunction(e) {
e.parentNode.querySelector(".dropdown-content").classList.toggle("show")
}
window.onclick = function(event) {
if (!event.target.matches(".dropbtn")) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
}
}
</script>
';
}
}
}
}
$userPostSTMT->free_result();
$userPostSTMT->close();
$userInfoSTMT->free_result();
$userInfoSTMT->close();
}
I needed to create a $Count variable that would assign a number for each post instead of using a random postid. I could then call element by classname using the count number to call an array of all the divs with a specific class name.
$Count = 0;
<div class="popup" class="popup">
<div class="overlay"></div>
<div class="content">
<div class="close-btn" onclick="togglePopup('.$PopCount.')">×</div>
<h1>Edit Post</h1>
<p>'.$Text.'</p>
<p>This Post ID keeps the value of the first loop iteration'.$PostID.'</p>
</div>
</div>
<div class="postBox">
<img class="postprofilepicture" src="../profilepictures/'.$ProfilePicture.'">
<p class="postusername">'.$UserName.'<p>
<p class="posttime">'.date('M jS, Y h:ia',strtotime($Date)).'<p>
<p>'.$Text.'</p>
<p>This Post ID Changes through for every new row'.$PostID.'<p>
<br>
<div class="dropdown">
<button onclick="myFunction(this)" class="dropbtn">···</button>
<div Id="myDropdown" class="dropdown-content">
View
Like
Show
Edit
<button onclick="togglePopup('.$PopCount.')">Popup</button>
</div>
</div>
</div>
<br>
<script>
function togglePopup(PopCount){
document.getElementsByClassName("popup")[PopCount].classList.toggle("active");
}
function myFunction(e) {
e.parentNode.querySelector(".dropdown-content").classList.toggle("show")
}
window.onclick = function(event) {
if (!event.target.matches(".dropbtn")) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
}
}
</script>
';
$PopCount++;
I am building a chat and i need to append content from the textarea to an inner div upon clicking send
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
the button and textarea code is
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Javascript
var sendButton= document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv= document.getElementById('inner');
var message=textArea.value;
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=meMessage;
});
var meMessage= '<div class="outgoing" id="outgoing">'+
'<div class="me" id="me"></div></div>';
What i am trying to do is show the text value of the text area to the inner div called 'me' when i click send
and also get the value of the textarea to save it to a database. How can i achieve this
First of all you shouldn't create html elements manually since they would be XSS vulnerable and read about escaping mechanics to prevent malicious code being injected.
Try using document.createElement('div'); method to create div with valid innerText.
later use method:
innerDiv.appendChild(createdElement);
To append element.
You could create builder to build html elements you need and you have to htmlEncode text that will be inside of div element.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
UPDATE: Extended snippet code. Removed Ids since they shouldn't be used there to create multiple message elements with same Id. Changed anchor to button.
You need to get the value of the textarea on click of the link
var sendButton = document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
innerDiv.innerHTML = `<div class="outgoing" id="outgoing">${textArea.value}
<div class="me" id="me"></div></div>`;
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn">Send</a>
You can use this. Youe message variable is not receiving the textarea value
var sendButton= document.getElementById('send-btn');
var innerDiv= document.getElementById('inner');
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=innerDiv.innerHTML+'<div class="outgoing" id="outgoing">'+document.getElementById('input').value+
'<div class="me" id="me"></div></div>';
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Maybe be replacing your js with that :
document.getElementById('send-btn').addEventListener('click',
function(){
var userInput = document.getElementById('input').value;
if(userInput) { document.getElementById('me').innerHTML += '<br>' + userInput; }
}
);
That should let you go a step forward... And good luck for saving to DB.
innerDiv.append(message)
instead of
innerDiv.innerHTML=message
I am trying to create a button using array but when i try to write text in text input and try to create a button it doesn't change the value.
function ready() {
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns() {
var btn = $("<button>" + family[i] + "</button>")
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i = 0; i < family.length; i++) {
btns();
}
$(submit).on("click", function() {
var textBtn = text.val();
family.push(textBtn);
btns();
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>
Is this what you are looking for? The code is commented to show you the steps
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
// for each family add a button
const buttons = family.map(el => $(`<button data-search="${el}">${el}</button>`));
$('#buttons').append(buttons);
function addButton() {
// get the value of the text input
const val = $('#button-text').val();
// if the value is not empty
if (val.trim().length) {
// create the new button and append it
const btn = $(`<button data-search="${val}">${val}</button>`);
$('#buttons').append(btn);
// add the val to the family array
family.push(val);
// add the button to the buttons array
buttons.push(btn);
// reset the input field
$('#button-text').val('');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttons">
</div>
<div>
<input type="text" id="button-text"/>
<button onClick="addButton()">Add Button</button>
</div>
The issue with your existing code is that you have declared the variable i in your for loop, but you are not incrementing the value when you manually add the new button.
If you update your submit button click event as follows, you will accomplish what you are looking for:
$(submit).on("click", function(){
var textBtn = text.val();
family.push(textBtn);
console.log(family);
btns();
i++; // Added the increment of 'i' here.
});
However, I am sure there's a much more eloquent way of solving this problem that doesn't involve keeping track of the array index.
Few things here
You may not need to create the input and the button using js. You can create it using html only
The i in the for loop is global, put a keyword before it and then pass the family[i] to the btns function
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns(val) {
var btn = $("<button>" + val + "</button>")
$(btn).attr("data-search", val)
$(btn).appendTo("#buttons")
}
for (let i = 0; i < family.length; i++) {
btns(family[i]);
}
$("#submitBtn").on("click", function() {
var textBtn = $("#submitIp").val();
btns(textBtn);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit">
<input type='text' id='submitIp' name='text'><button id='submitBtn'>Submit</button>
</div>
</div>
</div>
</div>
</body>
here, your loop is the main problem...you need to add element singularly
function ready(){
var family = ["demo1","demo2","demo3","demo4","demo5","demo6"];
function btns(){
var btn = $("<button>" + family[i] + "</button>");
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i=0; i < family.length; i++){
btns();
}
$(submit).on("click", function(){
var textBtn = text.val();
// family.push(textBtn);
var btn = $("<button>" + textBtn + "</button>");
$(btn).attr("data-search", textBtn)
$(btn).appendTo("#buttons")
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>
Also, I haven't change your code..just pasted your code on the correct block :)
you are missing selector while getting input val
function ready() {
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns() {
var btn = $("<button>" + family[i] + "</button>")
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i = 0; i < family.length; i++) {
btns();
}
$(submit).on("click", function() {
var textBtn = $( "input[name='text']" ).val();
family.push(textBtn);
btns();
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>
You're referring i in your btns function. The recommended way is to create a scope for any variable. I prefer to use let and const to scope the variables.
You have to move the iteration into the btns function and create another function which is solely responsible to create a button with the text passed as a parameter. And call the create button function from your btns function. And easily you can reuse the create button function even for your click event handler.
The sample code can be found here: https://codesandbox.io/s/pop7vkzpx
I want to loop through a JavaScript object and repeat an html script as many times as the object length.
Here, I have the following in a script tag
<script>
var obj;
ipcRenderer.on('requests-results', (event, hosSchema) => {
obj = hosSchema
})
</script>
obj is an array retrieved from Mongo database as the picture below shows:
and I have the following inside <body> tag:
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">.1.</span>
<p>.2.</p>
</div>
<div class="card-action">
.3.
.4.
</div>
</div>
</div>
</div>
How can I loop through obj to repeat the code between <div> tag as many times as obj.length?
I would suggest you to use Handlebars as #Amit mentioned.
first move out the code inside <div id="page-inner"> as below:
<div id="page-inner">
</div>
<script id= "requests-template" type="text/x-handlebars-template">
<div class="row">
{{#each requests}}
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">{{this.fieldName}}</span>
<p>{{this.fieldName}}</p>
</div>
<div class="card-action">
{{this.fieldName}}
{{this.fieldName}}
</div>
</div>
</div>
{{/each}}
</div>
</script>
Then inside another script page of type text/javascript you create the requests and assigned obj/hosSchema to it as below:
<script type="text/javascript">
var requestInfo = document.getElementById('requests-template').innerHTML;
var template = Handlebars.compile(requestInfo);
var requestData = template({
requests: obj
})
$('#page-inner').html(requestData);
</script>
NOTE: you need handlebars package installed (npm install handlebars --save)
Use templating script like Handlebars.js, Mustache.js or underscore.js.
Check below link for more description.
http://www.creativebloq.com/web-design/templating-engines-9134396
Try this:
var divlist = document.getElementsByTagName['div'];
var duplicate = null;
var rowIndex = -1;
var found = false;
for(var i = 0;i<obj.length;i++)
{
if(!found)
for(var p = 0;p<divlist.length;p++)
{
if(rowIndex != -1 && duplicate != null)
{
//set a Boolean to true and break
found = true;
break;
}
if(divlist[p].className == "col-md-4 col-sm-4")
{
//copy the element
duplicate = divlist[p];
}
else if(divlist[p].className == "row")
{
//identify the row's index
rowIndex = p;
}
}
//append the duplicate
divlist[rowIndex].appendChild(duplicate);
}
I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.