hello everybody ı have a question
this is my jquery code
<script type="text/javascript">
$('#com').keypress(function (event) {
var comm = $(this).val();
var keycode = (event.keycode ? event.keycode : event.which);
if (keycode == 13) {
var comm = $("#com").val();
alert(comm);
var hidid = $("#hidid").val();
alert(hidid);
$.ajax({
cache: false,
type: "POST",
url: "/Home/postComment",
datatype: "json",
data: { comment: comm, hidid: hidid },
error: function () {
alert("error ");
},
success: function () {
window.location.href = "/Home/Index";
}
});
}
event.stopPropagation();
});
</script>
and I am calling it in controller like this
[HttpPost]
public JsonResult postComment(string comment,int hidid)
{
Repository<whichOne> _rwo = new Repository<whichOne>();
Repository<Comment> _rc = new Repository<Comment>();
int _userId = Convert.ToInt32(Session["_userId"]);
Comment _comment = new Comment
{
userId = _userId,
comment = comment,
createDate = DateTime.Now,
isValid = true,
whichOneId = hidid,
};
_rc.Add(_comment);
_rc.Save();
return Json(new { success = true });
}
and I have data which are coming from database and I am trying to get id's of my datas and take comment to post from input
#foreach (var item in Model._mywhichOneHelper)
{
#Html.Hidden("hidid",#item.id)
<input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">}
however I can only reach first data when I hit enter after writing something.
Keypress is not working for other datas what can I do for this?
as you see when I write and click enter to first input it works but when I tried this for other datas nothing happens. thank you very much.
The problem here is your jQuery selector is only finding the first element, since it only expects one element to have an id (ids are supposed to be unique).
It is not a good practice to have multiple elements with the same id - this is part of your problem. If you can redesign your markup so that the elements have unique id's, but share a class (such as class="com") then you can easily write jQuery selectors to find them. In this case, there is still a workaround, you can use a jQuery selector like so: [id=com] instead of #com and this will find all the matching elements instead of only looking for one (expected) element with that unique id.
Also note I had to change your event handler so that it did not use another jQuery selector, but rather passed the value $self into the closure so that it held the correct unique instance instead of always finding the first.
$(function() {
$("[id=com]").keypress(function(event) {
var $self = $(this);
var comm = $self.val();
var keycode = (event.keycode ? event.keycode : event.which);
if (keycode == 13) {
var comm = $self.val();
alert(comm);
event.stopPropagation();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
<input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
<input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
Even better would be to use unique id's, and select via class, like so:
$(function() {
$(".com").keypress(function(event) {
var $self = $(this);
var comm = $self.val();
var keycode = (event.keycode ? event.keycode : event.which);
if (keycode == 13) {
var comm = $self.val();
alert(comm);
event.stopPropagation();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" class="pull-left input-sm form-control com" id="com1" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
<input type="text" class="pull-left input-sm form-control com" id="com2" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
<input type="text" class="pull-left input-sm form-control com" id="com3" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
<br />
Related
I' trying to build a form in which the users can change the values of two password inputs, one for a password and a second one to verify the password.
So in order to make the user aware of what he types and to make sure both of his/her password match with one another and tried to implemente a method in which he can just check a checkbox to show his password.
The current javascript method works with just one input but I would like to have it working with both input and not just one. I would like as well to show the password of both input without having to check their own corresponding checkbox(for example if a check one checkbox it should display text in both inputs).
This is the current javascript method that I have:
// First Code //
function addEvent (el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function () {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
function removeEvent(el, event, callback) {
if ('removeEventListener' in el) {
el.removeEventListener(event, callback, false);
} else {
el.detachEvent('on' + event, el[event + callback]);
el[event + callback] = null;
el['e' + event + callback] = null;
}
}
// Second Code //
(function() {
var pwd = document.getElementById('password');
var chk = document.getElementById('showpass');
addEvent(chk, 'change', function(e) {
var target = e.target || e.srcElement;
try {
if (target.checked) {
password.type = 'text';
} else {
password.type = 'password';
}
} catch(error) {
alert('This browser cannot switch type');
}
});
}());
<!-- First Password -->
<div class="form-group">
<label for="password">Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password" value="" id="password" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
<!-- Second Password -->
<div class="form-group">
<label for="password2">Confirm Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password2" value="" id="password2" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
Thanks in advance.
Change the type of both inputs at once:
var pwd = document.getElementById('password');
var confirm = document.getElementById('password2');
...
if (target.checked) {
pwd.type = 'text';
confirm.type = 'text';
} else {
pwd.type = 'password';
confirm.type = 'password';
}
Added a little fiddle to toggle the password type.
https://jsfiddle.net/xpvt214o/321232/
JS
var $vp = $('.vp');
$vp.on('click', function() {
var $target = $(this).siblings('input[name*="password"]');
if ($target.attr('type') == "password") {$target.attr('type','text');}
else {$target.attr('type','password');}
});
HTML
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 1</p>
<input type="password" name="password" val="" />
<span class="vp">View password</span>
</div>
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 2</p>
<input type="password" name="password2" val="" />
<span class="vp">View password</span>
</div>
The function looks for the click event of the span "vp" and get's its sibling input element, checks the type attribute and toggles it to and from text/password. The name of the inputs must contain "password" (in lowercase).
I have created form fields with a button.
I need the url of the button to change depending on the data entered in the Last name field. The Booking reference field does not effect the url
Example: User enters "John" in the last name field the button should have the url: http://www.john.com
Example: User enters "Henry" in the last name field the button should have the url: http://www.henry.com
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
You can use blur event on lastname to achieve this,
$('input[name=lastname]').on('blur', function(){
debugger
var lastName = $('input[name=lastname]').val()
//check if last name is there
if(lastName.length !== 0){
var link = 'http://www.'+ lastName +'.com';
$('.btn.btn-info').attr('href',link);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
My answer in ES6 style:
https://codepen.io/powaznypowazny/pen/GvxGMY
function retrieveURL() {
const anchor = document.querySelector('.btn.btn-info');
const input = document.querySelector('input[name=lastname]');
input.addEventListener('keyup', () => {
let value = input.value.toLowerCase();
anchor.href = `http://www.${value}.com`;
});
}
document.addEventListener("DOMContentLoaded", function(event) {
retrieveURL();
});
Try this:
$(document).ready(function()
{
$('.btn btn-info').click(function() {
var value = $("input[name='lastname']");
if(value.length > 0)
{
var hrefVal = $('a').attr('href');
hrefVal.replace('example' , value);
$('a').attr('href' , hrefVal);
}
});
});
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
I have fields in form which I add dynamically. How can I check if values of these fields unique?
HTML:
<div class="inputs">
<input type="text" class="form-control" id="regSection" name="regSection[]" required="required">
</div>
ADD
JavaScript:
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" id="regSection" name="regSection[]">').fadeIn('slow').appendTo('.inputs');
});
I've removed the id from the input as ID's must be unique.
This code will return found id the values in textbox repeat. Otherwise, it will return not found.
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" n ame="regSection[]">').appendTo('.inputs');
});
$('#check').click(function(e){
var arr = [];
var found = 0;
$('.inputs input').each(function(){
var myVal = $(this).val();
if(arr.includes(myVal))
found++;
else
arr.push(myVal);
});
if(found)
console.log('found');
else
console.log('unique');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<input type="text" class="form-control" name="regSection[]" required="required">
</div>
ADD
<button id="check">Check</button>
HTML:
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;"></div>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;"></div>
JQuery:
<script type="text/javascript">
$(document).ready(function() {
// Add onclick handler to checkbox w/id checkme
$('.showimage').click(function() {
var id = $(this).attr('id');
var ret = id.split("_");
var str1 = ret[1];
//alert(str1);
var id = $(this).attr('id');
var ret = id.split("_");
var str2 = ret[1];
//alert(str2);
//$(".icon_"+id).show();
// $("#icon").show();
if (str1 == str2) {
alert(str1);
$(".icon_" + str1).show();
//exit;
//alert("hi")
} else {
alert("sec");
$(".icon_" + str1).hide();
}
});
});
</script>
why not hide the else part
Your question: why not hide the else part?
That is because of $(this) it refers to the current element which have got the selector's context the event has raised on. So,
var id = $(this).attr('id');
The above variable has been used two times and both refers to the same object. So in the if condition:
if (str1 == str2) {
both values are always same and thus else never gets executed.
Better to use .focus()/.blur() events with .toggle(condition):
$(function(){
$('.showimage').on('focus blur', function(e){
$(this).next('div').toggle(e.type === "focus")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;">one</div><br>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;">two</div>
input[type="text"] {} input[type="text"] + div {
display: none;
}
hr {} input[type="text"]:focus + div {
display: inline-block;
/* added for style you can also use display:block */
}
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon">test1</div>
<hr>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon">test2</div>
I'm trying to show a div if all fields of a HTML form are filled with at least one character.
<input name="name" id="name" value="" required placeholder="Name"></input>
<input name="surname" id="surname" value="" required placeholder="Surname"></input>
<input name="email" id="email" value="" required placeholder="Email"></input>
<textarea name="comments" value="" required placeholder="Comments"></textarea>
<div id="test" style="display:none;">test</div>
and I've got this script
<script type="text/javascript">
if(document.getElementById('name').value!='' &&
document.getElementById('surname').value!='' &&
document.getElementById('email').value!='' &&
document.getElementById('message').value!=''){
document.getElementById('test').style.display = 'block';
}
</script>
but it doesn't work. Why? I tried to move the script from top to the bottom of the file but the div 'test' is always hidden. what is wrong with my sciript?
You have two errors, first you have not assigned any ID to your textarea which you are using in your script. Second, the function must be called upon everytime the user makes any change, so you need to bind the onchange event.
So, it should be:
HTML:
<input name="name" id="name" value="" required placeholder="Name" onchange="myUpdateFunction()"></input>
<input name="surname" id="surname" value="" required placeholder="Surname" onchange="myUpdateFunction()"></input>
<input name="email" id="email" value="" required placeholder="Email" onchange="myUpdateFunction()"></input>
<textarea name="comments" id="message" value="" required placeholder="Comments" onchange="myUpdateFunction()"></textarea>
<div id="test" style="display:none;">test</div>
JavaScript:
<script type="text/javascript">
function myUpdateFunction() {
if(document.getElementById('name').value!='' &&
document.getElementById('surname').value!='' &&
document.getElementById('email').value!='' &&
document.getElementById('message').value!='') {
document.getElementById('test').style.display = 'block';
}
}
</script>
You need to call that script every time a field is changed.
For instance:
<input name="name" id="name" value="" required placeholder="Name" onchange="myFunction()"></input>
etc.
<script type="text/javascript">
function myFunction() {
if(document.getElementById('name').value!='' &&
document.getElementById('surname').value!='' &&
document.getElementById('email').value!='' &&
document.getElementById('message').value!=''){
document.getElementById('test').style.display = 'block';
}
}
</script>
I see you linked jquery. Why not use it if you have it?
$('input').on('change', function(){
if($('#name').val() != '' && $('#surname').val() != '' && $('#email').val() != '' && $('#comments').val() != ''){
$('#test').show();
}else{
//This part is optional
$('#test').hide();
}
});
You should also add id="comments" in your textarea
The first issue is when the script is running. As coded it will run as soon as the page renders the script, and never again.
You will probably want to wire it up to the on change event of each text box so you can know when to show the hidden field.
Second, where is the "message" element? Is that supposed to be comments? If so, comments is missing an Id (has a name but no Id)
http://jsfiddle.net/7hafkwhj/1/
First of all it could be a good idea to wrap your elements inside an html tag form:
<form id="form">
<input name="name" type="text" placeholder="Name" required></input>
<input name="surname" type="text" placeholder="Surname" required></input>
<input name="email" type="email" placeholder="Email" required></input>
<textarea name="comment" placeholder="Comments" required></textarea>
</form>
<div id="message">Ok, roger</div>
Also, I don't understand why you should use jQuery for this kind of stuff. You can make the same thing using native Javascript:
(function() {
var form = document.getElementById('form'),
message = document.getElementById('message');
function makeCheck()
{
i = 0;
while(i < form.elements.length) {
if(form.elements[i].value === '')
{
return false;
}
i++;
}
return true;
}
function displayMessage()
{
if(makeCheck())
{
message.style.display = 'block';
}
else
{
message.style.display = 'hide';
}
}
for(i = 0; i < form.elements.length; i++)
{
form.elements[i].onkeyup = function () {
displayMessage();
};
}
})();