This click function was previously working, until i added another button and some php...curious what's preventing it from executing as before, i've checked issues from other questions:
-jquery is properly loaded before the local script
-all functions are wrapped in .ready() [Why is this jQuery click function not working?
I found an interesting post about delegated event handling here: Jquery button click() function is not working
But i don't understand if or why this would apply to my situation...and if it does can someone explain to me its significance?
Javascript:
jQuery ( document ).ready( function ( $ ) {
function initColorPicker0 () {
for ( x=0; x < 4; x++ ) {
var canvasEl0 = document.getElementById('colorCanvas0');
var canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function ( mouseEvent0 ) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $ ( '#bannerColor' );
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")" );
}
}
function demoBanner () {
// set click handler
$( '#demo' ).click( function () {
// store input values
var formObject = {
"prompt": document.getElementById('prompt').value,
"c2a" : document.getElementById('c2a').value,
"bannerColor" : document.getElementById('bannerColor').value,
}
//apply input values to style of new content
var newContent = " <div style='height: auto; padding: 15px 0px; margin: 0px -15px; background-color:" + formObject.bannerColor + ";'> <a href='#'> <p style=' margin-top: 0px; margin-bottom: 0px; text-align: center; color:" + formObject.promptTextColor + ";'>"+ formObject.prompt + " <a style='padding: 5px 12px; border-radius: 7px; background-color:" + formObject.c2aBG + "; color:" + formObject.c2aTextColor + " ' href='#'> <em> " + formObject.c2a + " </em> </a> </p> </a> </div>";
//set input as html content of demo
$( 'div.demo' ).html( newContent );
})
}
// called functions
$ ( function () {
initColorPicker0();
demoBanner();
});
});
HTML:
<div id="demo" class="demo"></div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>
<!--jquery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- local JS -->
<script src="http://localhost:8888/vorotech_site/js/banner-tool.js"> </script>
EDIT: $( '#demo' )
First of all, for .click(), it passes an event to the callback. For type="submit", this includes submitting the form. Would advise using .preventDefault().
Here is an example including some jQuery cleanup. Also tried to retain proper object indexes.
$(function() {
function initColorPicker0() {
var canvasEl0, canvasContext0;
for (x = 0; x < 4; x++) {
canvasEl0 = $('#colorCanvas0')[0];
canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function(mouseEvent0) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $('#bannerColor');
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")");
};
}
function demoBanner() {
// set click handler
$('#demo').click(function(e) {
e.preventDefault();
// store input values
var formObject = {
prompt: $('#prompt').val(),
c2a: $('#c2a').val(),
bannerColor: $('#bannerColor').val(),
};
//apply input values to style of new content
var newContent = $("<div>").css({
height: "auto",
padding: "15px 0px",
margin: "0px -15px",
"background-color": formObject.bannerColor,
});
$("<a>", {
href: "#"
}).appendTo(newContent);
$("<p>")
.css({
"margin": "0",
"text-align": "center ",
color: formObject.prompt
})
.html(formObject.prompt)
.appendTo($("a", newContent));
$("<a>", {
href: "#"
}).css({
padding: "5px 12px",
"border-radius": "7px",
"background-color": formObject.c2a,
color: formObject.c2a
}).html("<em>" + formObject.c2a + "</em>").appendTo("p", newContent);
//set input as html content of demo
$('div.demo').html(newContent);
});
}
// called functions
initColorPicker0();
demoBanner();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo" class="demo">DEMO</div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>
Related
I have a simple HTML form and am using JavaScript to display the entered value to the webpage, but everytime I hit submit the webpage reloads.
I have read the question at Webpage reloading on submitting form but that is jQuery and e.preventDefault(); isn't working in my case.
How to stop the page from reloading?
I have the following code:
function myFunction() {
var pm1, sqrtInt, pm2, constInt;
pm1 = document.getElementById("pm1").value;
pm1 = document.getElementById("sqrtInt").value;
pm1 = document.getElementById("pm2").value;
pm1 = document.getElementById("constInt").value;
document.getElementById("proof").innerHTML =
'<br>pm1 = ' + pm1 +
'<br>sqrtInt = ' + sqrtInt +
'<br>pm2 = ' + pm2 +
'<br>constInt = ' + constInt;
}
#proof {
background: black;
color: yellow;
width: 100%;
height: 20%;
}
<div>Form Trial</div>
<div>
<form onsubmit="myFunction()">
<div>
<select class="uk-select" id="pm1">
<option>Minus (-)</option>
<option>Plus (+)</option>
</select>
</div>
<div>
<input class="uk-input" type="text" placeholder="Square Root" id='sqrtInt'>
</div>
<div>
<select id="pm2">
<option>Minus (-)</option>
<option>Plus (+)</option>
</select>
</div>
<div>
<input type="text" placeholder="Constant" id='constInt'>
</div>
<div>
<input type="submit" value='submit'>
</div>
</form>
</div><br><br>
<div id="proof"></div>
Two things to do:
Add return to the onsubmit code:
<form onsubmit="return myFunction()">
Add at the end of your myFunction function:
return false;
function myFunction() {
var pm1, sqrtInt, pm2, constInt;
pm1 = document.getElementById("pm1").value;
pm1 = document.getElementById("sqrtInt").value;
pm1 = document.getElementById("pm2").value;
pm1 = document.getElementById("constInt").value;
document.getElementById("proof").innerHTML =
'<br>pm1 = ' + pm1 +
'<br>sqrtInt = ' + sqrtInt +
'<br>pm2 = ' + pm2 +
'<br>constInt = ' + constInt;
return false; // <---------
}
#proof {
background: black;
color: yellow;
width: 100%;
height: 20%;
}
<div>Form Trial</div>
<div>
<form onsubmit="return myFunction()">
<div>
<select class="uk-select" id="pm1">
<option>Minus (-)</option>
<option>Plus (+)</option>
</select>
</div>
<div>
<input class="uk-input" type="text" placeholder="Square Root" id='sqrtInt'>
</div>
<div>
<select id="pm2">
<option>Minus (-)</option>
<option>Plus (+)</option>
</select>
</div>
<div>
<input type="text" placeholder="Constant" id='constInt'>
</div>
<div>
<input type="submit" value='submit'>
</div>
</form>
</div><br><br>
<div id="proof"></div>
I'm trying to add an input field when clicking on add, and it should be removed when clicking on delete click.
Here is JS Bin link:
JS issue with deletion
var newTextBoxDiv;
var rowCount = 0;
var counter = 1;
var delCounter = 1;
$(document).ready(function() {
$(document).on('focus', '.txtFocus', function() {
$(this).next('.clearContent').hide()
});
$(document).on('focusout', '.txtFocus', function() {
$('.clearContent').show()
})
});
function addTags(obj) {
var newTextBoxDiv = '<div class="col-md-4 TextBoxMainDiv"><div style=""><div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;"><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" ><span class="clearContent"><i class="fas fa-times"></i></span> </div><div style="width: 15%;display: inline-block;text-align:right;"><span id="addMore" onClick="addTags(this);"><i class="fas fa-plus-square"></i></span></div></div></div>';
$(obj).hide();
$("#tagElement").append(newTextBoxDiv);
$('.txtFocus').focus();
counter++;
if (counter == 1) {
$(obj).show()
}
}
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
if (counter == 1) {
$('#addMore').show()
}
}
<div class="row">
<div id="tagElement">
<div> </div>
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;">
<input type="text" class="txtFocus" required placeholder="Add Tag" id="textBox" autocomplete="false" autofocus="autofocus" style="width: 100%">
<span class="clearContent">
Add
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
cancel
</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I manage to add the input fields properly, but have issues deleting them. They seem to be deleted randomly.
I think the add and delete button are mixed up, but I couldn't spend time on analysing the code because it's too much code for something that does very little. The following demo:
has a single button that adds a row of form controls:
a checkbox
a text input
a button that deletes it's own row as well as itself.
Demo
var index = 0;
var template = `
<figure class='frame'><input class='status' type='checkbox'><label class='tag'></label><input class='text' type='text' placeholder='Enter New Task'><button class='del' type='button'>➖</button></figure>`;
$('.set').on('click', 'button', function(e) {
if ($(this).hasClass('add')) {
index++;
$('.set').prepend(template);
$('.status:eq(0)').attr('id', 'chx' + index);
$('.tag:eq(0)').attr('for', 'chx' + index);
} else {
$(this).prevUntil('.del, .add').add(this).remove();
}
});
.set {
position: relative;
padding: 2px 0 1px 2px;
min-height: 28px;
border-radius:7px;
}
.frame {
padding: 0;
margin: 0;
min-width:90vw;
}
.add {
position: absolute;
right: 6px;
top: 3px;
display:block;
}
.status {
display: none
}
.tag {
display: inline-table;
font-size: 28px;
line-height: 1;
vertical-align: middle
}
.tag::before {
content: '\2610';
}
.status:checked+.tag::before {
content: '\2611'
}
.text {
display:inline-table;
width: 75%;
margin: 2px 5px 0
}
<form id='ui'>
<fieldset class='set'>
<figure class='frame'>
<input id='chx0' class='status' type='checkbox'>
<label for='chx0' class='tag'></label>
<input class='text' type='text' placeholder='Enter New Task' style='margin:2.5px 2px 0 0' autofocus>
<button class='del' type='button'>➖</button>
</figure>
<button class='add' type='button'>➕</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think your code's logic is working, however, the icon for addition and deletion of inputs is not being rendered.
You can replace your newTextBoxDiv with this:
var newTextBoxDiv = `
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px; float:left; width:80%;">
<input type="text" name="textbox${counter}" id="textbox${counter}" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" >
<span class="clearContent">
Delete<i class="fas fa-times"></i>
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
Add
</span>
</div>
</div>`;
Notice that I added the word "Add" and "Delete" between the tags, so that you have something to click on
Also, I think you need to swap the word "Add" and "Cancel" in the initial HTML to convey a clearer message, as they are now doing the opposite thing.
Another fix that's needed is to replace the id="addMore" with class="addMore"
<span class="addMore" onClick="addTags(this);">
Since id is meant to be unique. In your code, however, when you append new element, you added new elements with duplicate id, making jquery's selector not selecting the element you want.
After replacing id with class, you also need to change the deleteTag function to select the last "addMore" span and show it.
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
$('.addMore').last().show();
}
For the layout, you need to do it with css, removing float and setting the div tag with appropriate width and display: inline-block. I suggest you use a separate css file to style the elements instead of doing it inline.
function deleteTodo() {
$(this).parent().remove();
}
function addTodo() {
var inputTemplate =
'<div class="todo-input-wrapper">' +
'<input class="todo-input" type="text" placeholder="Add Tag" />' +
'<button class="delete-button">Delete</button>' +
'</div>';
$('.todo-wrapper').append(inputTemplate);
$('.delete-button').last().on('click', deleteTodo);
$('.todo-input').last().focus();
}
$(document).ready(function () {
$('.delete-button').on('click', deleteTodo);
$('.add-button').on('click', addTodo);
});
.todo-wrapper {
display: inline-block;
width: max-content;
font-size: 0;
}
.todo-input-wrapper {
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="todo-wrapper">
<div class="todo-input-wrapper">
<input class="todo-input" type="text" placeholder="Add Tag" />
<button class="delete-button">Delete</button>
</div>
</div>
<button class="add-button">Add</button>
$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
I'm having an issue getting this snippet to run. form-1 is hidden, backButton-1 is created after the end of form-2 and only after form-1 has been hidden. I want backButton-1 to empty out form-2 and unhide form-1 but the .click event isn't firing.
Here's the code:
$(document).ready(function() {
var playersName = '';
var gameName = '';
var playersNameArray = [];
$("#submit-1").click(function() {
playersName = $("#input_players").val();
gameName = $("#input_game").val();
$("#form-1").hide();
gameName = gameName.toLowerCase();
gameName = gameName.charAt(0).toUpperCase() + gameName.substr(1);
function makeArray(string) {
string = string.replace(/\s/g, '');
var array = string.split(",");
for (let i = 0; i < array.length; i++) {
array[i] = array[i].toLowerCase();
array[i] = array[i].charAt(0).toUpperCase() + array[i].substr(1);
}
playersNameArray = array;
}
makeArray(playersName);
function makeScores(array) {
$("#container-1").prepend("<p>Input " + gameName + " scores:</p>");
for (let i = 0; i < array.length; i++) {
var scoreDiv = document.createElement("div");
scoreDiv.className = "score";
scoreDiv.id = "score-" + (i + 1);
var scoreInput = document.createElement("input");
$(scoreInput).attr('type', 'text');
scoreInput.id = "scoreInput-" + (i + 1);
$("#form-2").append(scoreDiv);
$("#score-" + (i + 1)).append("<div class='scoreName'>" + array[i] + "</div>");
$("#score-" + (i + 1)).append(scoreInput);
}
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
);
}
makeScores(playersNameArray);
});
$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
$("#submit-2").click(function() {
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
You are saying the button is being created, which means that jQuery cannot add an event listener on load. Either create the listener together where you create the button, or use propagation.
// Create button, add to DOM
$("<div>New div</div>").appendTo("body")
.click(function() {
// Attach click event listener
alert("Works!");
});
// Or using propagation
$("body").on("click", "#test", function() {
alert("Works too!");
});
$("<div id='test'>New div</div>").appendTo("body");
Note that the second approach works irrespective of where you attach the event listener to body, be it before or after creating the new item.
In your case, I suggest:
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
).on("click", "#backButton-1", function() {
$("#form-2").empty();
$("#form-1").show();
});
Try adding your links at the bottom
and add the following link in your head
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script> <!-- <<<< This ONE-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input**strong text**_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
I have this code (snippet). If you type your name, it will add it below automatically.
If you click "Add member" and type a name inside the appended input, it appears below too (on its respective "Hello, ...")
If you do it again, this time won't work, because the jscode only applies to the first appended elements.
My question is: how do I apply this jscode with with a third or fourth member, and so on?
PS. Another question: how do I make it unable to remove the first input text (so it is required to have at least 1 member)?
var name1 = document.getElementById('first');
name1.addEventListener('input', function() {
var result = document.querySelector('span.one');
result.innerHTML = this.value;
});
$('.add').click(function() {
$('.block:last').after('<div class="block"><input type="text" id="X"><span class="remove">Remove member</span><br><br></div>');
$('.hello:last').after('<div class="hello">Hello, <span class="name"></span><br><br></div>');
var name1 = document.getElementById('X');
name1.addEventListener('input', function() {
var result = document.querySelector('span.name');
result.innerHTML = this.value;
});
});
$('.optionBox').on('click', '.remove', function() {
$(this).parent().remove();
$('.hello:last').remove();
});
.block {
display: block;
}
input {
width: 50%;
display: inline-block;
}
span.add, span.remove {
display: inline-block;
cursor: pointer;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="optionBox">
<div class="block">
<span class="add">Add member</span>
<br><br>
</div>
<div class="block">
<input type="text" id="first"> <span class="remove">Remove member</span><br><br>
</div>
</div>
<div class="newmember">
</div>
<br>
<div class="hello">
Hello, <span class="one"></span><br><br>
</div>
I have done a bit of workout for you. Please check it. I think this is what you are looking for. I am adding same id and class attr for the input and the div to display the content.
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class ="' + x + '" ><input type="text" class= "' + x + '" name="mytext[]"/>Remove</div>'); //add input box
$('.hello:last').after('<div class="hello" id = "' + x + '" >Hello, <span class="name"></span><br><br></div>');
$('input').on('input', function(e) {
divtoappend = $(this).attr('class');
var val = "";
var val = $(this).val();
var sel = "#" + divtoappend + " span";
$(sel).text('');
$(sel).append(val);
});
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
var rem = $(this).parents('div').attr('class');
$('#' + rem).remove();
$(this).parent('div').remove();
x--;
});
});
.block {
display: block;
}
input {
width: 50%;
display: inline-block;
margin : 4px;
}
span.add, span.remove {
display: inline-block;
cursor: pointer;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" class="1" name="mytext[]"></div>
</div>
<div class="hello" id="1">
Hello, <span class="1"></span><br><br>
</div>
Ok, I think we're all over-thinking this:
<div>
<button id="uxAddMember" class="btn btn-primary">Add Member</button>
</div>
<div class="container">
<div class="row" data-id="1">
<div class="form-control">
<input type="text" class="name" id="name" /> <span style="padding-left: 10px;"><button class="btn btn-warning">Remove Member</button>
</div>
</div>
</div>
<div>
<span id="uxHello"></span>
</div>
<script type="text/javascript">
$(document).ready(function() {
var rows = 1;
$('#uxAddMember').click(function() {
$('.container').append($('.row').attr('data-id', rows).html());
rows++;
});
});
$(document).on('keyup', '.name', function() {
$('#uxHello').html("Hello, " + $(this).val());
});
</script>
That doesn't include your removal functionality, but it takes care of the name output and adding new rows.
Can someone help me get the values of the firstName and the lastName from a paragraph that I click on so I can display them in another div. I only managed to get the whole text from the paragraph that I click on, but i need the values of the firstName and the LastName. Below is the commented code that I need help with. Thanks in advance.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
// $('#contacts').on('click', 'p', function (e) {
// $("#show-contact").show();
// $("#show-contact h2").text(newContact.firstName);
// $(".first-name").text(newContact.firstName);
// $(".last-name").text(newContact.lastName);
// });
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>
Wrap firstName and lastName with anchor tag (or etc) and get it over with this tag:
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
$(document).on('click', '.para',function(){
var fn = $(this).find('.fn').text();
var ln = $(this).find('.ln').text();
$('#show-contact').append('<p>First name: <span class="first-name">'+fn+'</span></p><p>Last name: <span class="last-name">'+ln+'</span></p>'); // Add
//$('#show-contact').html('<p>First name: <span class="first-name">'+fn+'</span></p><p>Last name: <span class="last-name">'+ln+'</span></p>'); // update
//console.log("first name is: " + fn + " last name is: " + ln);
});
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: <a class="fn">' + newContact.firstName + '</a> Last Name: <a class="ln">' + newContact.lastName + "</a></p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
// $('#contacts').on('click', 'p', function (e) {
// $("#show-contact").show();
// $("#show-contact h2").text(newContact.firstName);
// $(".first-name").text(newContact.firstName);
// $(".last-name").text(newContact.lastName);
// });
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
</div>
</div>
</div>
</div>
One possible solution is to extract firstname and lastname using substr as follows.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
$('#contacts').on('click', 'p', function (e) {
// Get current para's text
var txt = $(this).text();
// pre-define labels present in the text
var fnameLabel = 'First Name: ';
var lnameLabel = 'Last Name: ';
// define length of the labels
var fnameLabelLen = fnameLabel.length;
var lnameLabelLen = lnameLabel.length;
// define Index positions of the labels
var fnameLabelIdx = txt.indexOf(fnameLabel);
var lnameLabelIdx = txt.indexOf(lnameLabel);
// Get First Name value by calculating the Index position
// between labels first name and last name
var firstName = txt.substr(fnameLabelIdx+fnameLabelLen, lnameLabelIdx-fnameLabelLen);
// Get Last Name by calculating Index positions
// between lastname label and end of para
var lastName = txt.substr(lnameLabelIdx+lnameLabelLen, txt.length-lnameLabelLen);
$("#show-contact").show();
$("#show-contact h2").text(firstName);
$(".first-name").text(firstName);
$(".last-name").text(lastName);
});
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>
You can do this with regex.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
$("#show-contact").hide();
$('#contacts').on('click', 'p', function (e) {
var name = $(this).html();
var fname = name.match(/(?<=First Name: ).*?(?= Last)/);
var lname = name.match(/(?<=Last Name: ).*$/);
$("#show-contact").show();
$("#show-contact .first-name").html(fname);
$("#show-contact .last-name").html(lname);
});
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
#contacts>li:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>